不同Spring版本 方式不一样
第一种
String path = this.getClass().getClassLoader().getResource("").getPath() .concat("files/a.txt");
path = URLDecoder.decode(path);
File file = new File(path);
第二种
ClassPathResource classPathResource = new ClassPathResource("files/a.txt");
File file = classPathResource.getFile(); // 获取文件对象
第三种, 最有效
前面两种大多数情况 打包成jar运行 都是获取不到文件,war好像可以
jar 方式获取文件方式:
- 先获取 inputStream
- 然后在把 inputStream流 输出到硬盘文件
- 在获取这个硬盘文件
FileUtils
使用 org.apache.commons.io.FileUtils
需要加入 commons.io
maven依赖或者 jar包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
示例
// 获取输入流
Resource classPathResource = new ClassPathResource("/excel-templates/excel-dict-customs.xlsx");
InputStream inputStream = classPathResource.getInputStream();
/**
* 输出文件的路径
* @filed outFilePath 当前 程序jar路径, 比如当前 程序jar 在D:\my\jar, 那么路径就是 D:\my\jar + 在拼接上文件名称
*/
String outFilePath = ( new File(".")).getCanonicalPath().concat(String.format("/tmp-file-%s", System.currentTimeMillis()));
// 将 InputStream 复制输出到 指定文件上
File file = new File(outFilePath);
FileUtils.copyInputStreamToFile(inputStream, file);
// 关闭输入流
inputStream.close();
System.out.printf("文件是否存在: %s%n", file.exists());
操作完 File 记得删除文件