背景描述:SpringBoot项目构建打包生成的jar包,在资源文件夹下有个普通txt文件,路径:/templates/content.txt
方式一:
File file = new File(ResourceUtils.getURL("classpath:").getPath());
File templateFile = new File(file, "/templates/content.txt");
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
String tempStr;
while ((tempStr = reader.readLine()) != null) {
sbf.append(tempStr);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return sbf.toString();
方式二:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/content.txt");
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(inputStream));
String tempStr;
while ((tempStr = reader.readLine()) != null) {
sbf.append(tempStr);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return sbf.toString();