jar包部署读取不到resources下的文件 情景:idea下启动服务,正常读取。打成jar包部署到生产环境读取不到文件,报错。
目录结构:
bug信息:
出现异常啦:file:/data/service/app/dsc/dsc-be-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/sql/insertSql.txt (Is a directory),异常发生地: at java.io.FileInputStream.open0(Native Method)
java.io.FileNotFoundException: file:/data/service/app/dsc/dsc-be-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/sql/insertSql.txt (Is a directory)
出现异常啦:file:/data/service/app/dsc/dsc-be-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/sql/insertSql.txt (No such file or directory),异常发生地: at java.io.FileInputStream.open0(Native Method)
java.io.FileNotFoundException: file:/data/service/app/dsc/dsc-be-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/sql/insertSql.txt (No such file or directory)
2021-07-22 14:07:13.407 ERROR 1 --- [nio-9711-exec-4] c.c.b.common.base.BaseExceptionHandler : 出现异常啦:File 'file:/data/service/app/dsc/dsc-be-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/sql/insertSql.txt' does not exist,异常发生地: at org.apache.commons.io.FileUtils.openInputStream(FileUtils.java:299)
java.io.FileNotFoundException: File 'file:/data/service/app/dsc/dsc-be-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/sql/insertSql.txt' does not exist
问题代码:
本地idea启动是正常的。
String filePath = "sql/insertSql.txt";
URL url = this.getClass().getClassLoader().getResource(filePath);
File f = new File(url.getPath());
if(!f.exists()){
System.out.println(url.getPath()+"目录下文件不存在!");
f.mkdirs();
}
StringBuffer stringBuffer=new StringBuffer();//用于解析文件
StringBuffer stringBufferSql=new StringBuffer();//用户解析文件之后转换入库执行
InputStream inputStream=new FileInputStream(f);
byte[] buff=new byte[1024];
int btr=0;
while ((btr = inputStream.read(buff)) !=-1){
stringBuffer.append(new String(buff,0,btr,"UTF-8"));
}
inputStream.close();
String[] sqlArr=stringBuffer.toString().split("(\\s*\\r\\n)|(\\s*\\n)");
正确代码:
filePath通过getClassLoader()获取文件流,路径前面不加“/”。
不创建File对象,直接通过路径创建输入流。
String filePath = "sql/insertSql.txt";
//文件读取
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
StringBuffer stringBuffer=new StringBuffer();//用于解析文件
byte[] buff=new byte[1024];
int btr=0;
while ((btr = inputStream.read(buff)) !=-1){
stringBuffer.append(new String(buff,0,btr,"UTF-8"));
}
inputStream.close();
String[] sqlArr=stringBuffer.toString().split("(\\s*\\r\\n)|(\\s*\\n)");
原因:
Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它其实是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法都无法正确获取文件。
|