一般读取文件都喜欢使用相对路径或者绝对路径读取文件,例如:
String filePath = new File(ResourceUtils.getURL("classpath:").getPath()).getPath();
log.info("文件读取路径 ->" + filePath);
//获取项目工程当前所在路径
//在Linux环境下存在file:开头,会报错
filePath = filePath.replace("file:", "").replace("!", "");
fileInputStream = new FileInputStream(filePath + "/module/" + fileName);
这种方法在本地执行没有问题,但是在代码打成jar包后是会报错的, 这主要是因为jar包是一个单独的文件而非文件夹,绝对不可能通过"file:/e:/…/ResourceJar.jar/resource /res.txt"这种形式的文件URL来定位res.txt。但可以通过Class类的getResourceAsStream()方法来获取
InputStream fileInputStream = this.getClass().getResourceAsStream("/module/" + fileName);
这样就可以正常读取到文件了。
maven打包导致resource中的文件乱码解决方法:
<!-- 防止excel等文件乱码-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven.resources.plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>