SpringBoot读取resource目录下文件
1.使用ClassPathResource
ClassPathResource CPR = new ClassPathResource(path);//**path 不以’/'开头时默认是从此类所在的包下取资源**
InputStream inputStream =CPR.getInputStream();
2.使用getResourceAsStream
InputStream inputStream = this.getClass().getResourceAsStream(path);//path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从根下获取。
3.使用File
File file = new File(path);//**path为绝对路径**
InputStream inputStream = new FileInputStream(file);
该方式无法读取jar包中文件
最后
将字节流转化为字符流
Reader reader = new InputStreamReader(inputStream, "utf-8");
int ch = 0;
StringBuffer str = new StringBuffer();//可变字符串
while ((ch = reader.read()) != -1) {//使用read()方法将字符流的ASCII值添加到str中
str.append((char) ch);
}
reader.close();
jsonStr = str.toString();//转化为字符串