Java中静态资源路径找不到
想要读取一个json文件到String字符串中。
写了一个方法,但是执行时路径总是找不到。
修改后解决了问题。
原来的代码:
public String readFileAsString(String filePath) {
StringBuilder fileContents = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
fileContents.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
}
return fileContents.toString();
}
修改后的代码:
public String readFileAsString(String filePath) {
ClassPathResource classPathResource = new ClassPathResource(filePath);
StringBuilder fileContents = new StringBuilder();
try {
InputStream in = classPathResource.getInputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = reader.readLine()) != null) {
fileContents.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return fileContents.toString();
}