ClassPathResource classPathResource = new ClassPathResource("text/test.txt");
InputStream inputStream =classPathResource.getInputStream();
InputStream inputStream =
Thread.currentThread().getContextClassLoader().getResourceAsStream("text/test.txt");
InputStream inputStream =
ClassLoader.getSystemClassLoader().getResourceAsStream("xls010.xls")
InputStream inputStream = this.getClass().getResourceAsStream("/text/test.txt");
File file = ResourceUtils.getFile("classpath:text/test.txt");
InputStream inputStream = new FileInputStream(file);
前4种方法在项目文件或jar包时都能读取到, 原理是通过类加载器读取
第5种只能在项目文件中读取
new ApplicationHome().getDir().getPath();
方法1就是调用了方法2 System.getProperty("user.dir")
System.getProperty("user.dir")
String源码
private File findHomeDir(File source) {
File homeDir = source;
homeDir = (homeDir != null) ? homeDir : findDefaultHomeDir();
if (homeDir.isFile()) {
homeDir = homeDir.getParentFile();
}
homeDir = homeDir.exists() ? homeDir : new File(".");
return homeDir.getAbsoluteFile();
}
private File findDefaultHomeDir() {
String userDir = System.getProperty("user.dir");
return new File(StringUtils.hasLength(userDir) ? userDir : ".");
}
System.getProperty("user.dir")
SpringBoot读取Resource下文件的4种方法