首页 > 解决方案 > 访问 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);
    
}

}

标签: javajsonnullpointerexceptionresourcesexecutable-jar

解决方案


推荐阅读