java - 访问 jar 中的 Json 文件时 (java.lang.NullPointerException)
问题描述
我需要访问它存储在资源文件中的 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 助手类:
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);
}
}
解决方案
推荐阅读
- ios - 如何使特定侧的 UIVIEW 圆角半径不同?
- ios - 迭代 StackView,Swift
- javascript - 在邮递员的获取请求上加载“发送请求”
- javascript - 我需要一个全面的正则表达式来创建一个连字符的单词链接
- sql - 在 SQL Server 中根据 ID 查找数字的平均值
- jpa - 高级 JPA 查询/子查询
- ios - CollectionView didDeselectItemAt 没有被调用 CollectionView 中的单选
- php - 致命错误:require():需要打开失败
- parallel-processing - 每个任务 SLURM 多个节点
- javascript - 反应原生阻止按钮制造商的顶部不可点击