通过ClassPathResource获取文件路径,避免由于springboot项目打包后文件无法再到异常
package com.springboot_call_police.unit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ClassPathResource;
import java.io.*;
public class ReadJson {
public String ReadFile(String Path){
BufferedReader reader = null;
String laststr = "";
try{
FileInputStream fileInputStream = new FileInputStream(Path);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
reader = new BufferedReader(inputStreamReader);
String tempString = null;
while((tempString = reader.readLine()) != null){
laststr += tempString;
}
reader.close();
}catch(IOException e){
e.printStackTrace();
}finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return laststr;
}
public String urlUnit(int i){
String urlseed= null;
try {
//获取resources资源文件下的文件
ClassPathResource classPathResource = new ClassPathResource("json/UrlSeed.json");
//转文件类型
File file = classPathResource.getFile();
//通过获得的文件路径,读取文件中的内容
urlseed=ReadFile(file.getPath());
} catch (Exception e) {
e.printStackTrace();
}
return urlseed;
}
}