一 背景
在以前的单体应用中我们可以将文件存放在服务器中的指定目录,然后通过代码直接获取,而当我们在使用Docker容器发布的时候,由于每次镜像打包都会将文件清除(本人目前的理解),而挂载目录使用不是很熟练(我的理解挂载目录可以解决),所以通过下列方式来实现ClassPath下预存文件处理。
二 示例分析
直接向ClassPath目录下的文件读成文件流
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
try {
Resource resource = new ClassPathResource("/cert/**/wxjsapiapiclient_cert.p12");
File sourceFile = resource.getFile();
InputStream certStream = new FileInputStream(sourceFile);
this.certData = new byte[(int) sourceFile.length()];
certStream.read(this.certData);
certStream.close();
} catch (Exception e) {
System.err.print(e);
}
获取当前项目所在的绝对路径。
String path = System.getProperty("user.dir");
获取当前项目中,某相对路径下资源的绝对路径。
/**
* @author calm_encode
*/
public class ClassPathUtil {
public String getClassPath(String relativePath){
//获取ClassPath, relativePath 为资源的相对路径
String path = ClassLoader.getSystemResource(relativePath).getPath();
return path;
}
}
三 完整示例
String path = System.getProperty("user.dir");
System.out.println("path = " + path);
String paths = ClassLoader.getSystemResource("common-images/photoBook/back_cover.png").getPath();
System.out.println(paths);
结果:
个人使用的一些方式,希望对各位有用。后续完全理解挂载目录和Docker镜像容器细节再来完善。待续。。。