提问人:Mike 提问时间:10/19/2020 更新时间:10/19/2020 访问量:120
在 jar 中访问 Json 文件时 (java.lang.NullPointerException)
when accessing Json file in jar (java.lang.NullPointerException)
问:
我需要访问它存储在 Resources 文件中的 Json 文件中的一些数据。代码在eclipse中编译,但是当我尝试导出并作为JAR文件运行时,出现此异常:
Json 文件的位置为:
我尝试使用:
Thread.currentThread().getContextClassLoader() .getResourceAsStream(“AutomationJson.json”);
或
Thread.currentThread().getContextClassLoader() .getResourceAsStream(“/AutomationJson.json”);
Main(){
InputStream jsonFileStream = getClass().getClassLoader().getResourceAsStream("AutomationJson.json");
String jsonString = readFromJARFile();
jsonData();
}
private void jsonData() {
JsonNode node = null;
try {
node = JsonHelper.parse(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
secondUserName = node.get("secondUserName").asText();
password = node.get("password").asText();
}
public String readFromJARFile() throws IOException {
InputStreamReader isr = new InputStreamReader(jsonFileStream);
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
isr.close();
return sb.toString();
}
Json helper 类:
public class JsonHelper {
private static ObjectMapper objectMapper = getDefaultMapper();
static ObjectMapper getDefaultMapper() {
ObjectMapper defaultMapper = new ObjectMapper();
defaultMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return defaultMapper;
}
public static JsonNode parse(String src) throws JsonProcessingException {
return objectMapper.readTree(src);
}
}
答: 暂无答案
评论
getRessourceAsStream()
getRessource()
InputStreamReader isr = new InputStreamReader(jsonFileStream);
readFromJARFile
getRessource()
file:/D:/Project_File/Project_name/target/classes/AutomationJson.json
D:\Project_File/Project_name\src\main\resources/AutomationJson.json
jsonFileStream
readFromJARFile()