【jar包可行】在jar包中正确读取静态资源
使用getResourceAsStream()
InputStream stream = getClass()
.getClassLoader()
.getResourceAsStream("names.txt");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
String line;
while ( (line = br.readLine()) != null) {
System.out.println(line);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
【具体解释】getFile为什么在jar包中不行
我们本地读取文件的时候是使用spring自带的ResourceUtil.getFile("classpath:xxxx.txt"),该方法读取是本地的绝对路径,在我们ide开发工具中是没有问题的,因为文件就在磁盘上存储,读取当然也是通过文件存储的磁盘地址读取,但是我们的项目一旦 打包 成jar文件后,我们的所有文件都会在JVM中运行(都是加载到JVM中的),所以使用ResourceUtil.getFile("classpath:xxxx.txt")方法是不可以读取到的,在JVM中是没有绝对路径的,所有的路径都是依托于读取文件的当前类对应的classload来加载的,所以我们需要先获取到当前类的classload,然后通过classload的路径找文件相对于classload的相对路径。
【IDEA可行】在idea中可行但jar中不可行的读取resourece下静态文件的方法
方法一:
这种方案在jar包中也不行
String path = this.getClass().getClassLoader().getResource("names.txt").getFile();//注意getResource("")里面是空字符串
String filePath = null;//如果路径中带有中文会被URLEncoder,因此这里需要解码
Scanner myReader = null;
try {
filePath = URLDecoder.decode(path, "UTF-8");
System.out.println("打印路径:");
System.out.println(filePath);
File file = new File(filePath);
myReader = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
}
myReader.close();
方法二:
File file = ResourceUtils.getFile(patternNameFile);
Scanner myReader = new Scanner(file);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
参考博客:ResouceUtils.getFile()取不到Jar中资源文件源码-腾讯云开发者社区-腾讯云 (tencent.com)