测试项目的文件目录
1.获取文件根目录
String property = System.getProperty("user.dir");
输出结果为:
D:\DocumentH\PDFExport
2.获取资源路径(比如获取resources下的temp文件夹路径hello.ftl文件)
try {
File file = ResourceUtils.getFile("classpath:static\\temp");
System.out.println(file.getPath());
System.out.println(file.isDirectory());
System.out.println("-----------------------------------------------------");
File helloFile = ResourceUtils.getFile("classpath:static\\temp\\hello.ftl");
System.out.println(helloFile.getPath());
System.out.println(helloFile.isDirectory());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
输出结果为:
D:\DocumentH\PDFExport\target\classes\static\temp
true
-----------------------------------------------------
D:\DocumentH\PDFExport\target\classes\static\temp\hello.ftl
false
3.第2种方式在idea环境下获取资源路径没问题,但是将项目打成jar包,再运行就会出现如下问题:
java.io.FileNotFoundException: class path resource [static] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/export-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static
发现找不到,而且在D:/export-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static中间有!莫名其妙的出现
百度了好久大概意思是:在idea环境下,资源文件都以正常的磁盘路径存储;但是当打成jar包,该文件是存在jar包文件资源里,而不是真实存在于磁盘路径上。
而此时,我们需要换一种方式即:
InputStream inputStream=this.getClass().getResourceAsStream("/static/temp/hello.ftl");
可以将文件获取到,不过是以流的形式,然后我们可以将流转成我们自己想要的格式,下面的示例是转为File格式。
需要引入commons-io包
String property = System.getProperty("user.dir");
//在根目录生成一个文件
File targetFile = new File(property+"targetFile.ftl");
//将流转成File格式
FileUtils.copyInputStreamToFile(inputStream, targetFile);
再打包,掉接口,就没什么问题了。
建议:为了避免在发布的时候遇到各种坑爹问题,所以还是建议使用第三种。