在 jar 中访问 Json 文件时 (java.lang.NullPointerException)

when accessing Json file in jar (java.lang.NullPointerException)

提问人:Mike 提问时间:10/19/2020 更新时间:10/19/2020 访问量:120

问:

我需要访问它存储在 Resources 文件中的 Json 文件中的一些数据。代码在eclipse中编译,但是当我尝试导出并作为JAR文件运行时,出现此异常:

enter image description here

Json 文件的位置为:

Resource folder

我尝试使用:

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);
    
}

}

java json nullpointerexception 资源 executable-jar

评论

0赞 MDK 10/19/2020
异常发生在代码的哪一行中?这应该在异常的调用堆栈中的某个位置列出。如果替换 by 然后打印返回值,打印的路径是否与文件的实际路径匹配?getRessourceAsStream()getRessource()
0赞 Mike 10/19/2020
调用异常的行位于函数上 当我打印时,我得到 URL JSON 文件存在于此文件中,位于 @MDKInputStreamReader isr = new InputStreamReader(jsonFileStream);readFromJARFilegetRessource()file:/D:/Project_File/Project_name/target/classes/AutomationJson.jsonD:\Project_File/Project_name\src\main\resources/AutomationJson.json
0赞 Smile 10/19/2020
你能用可以编译的代码更新问题吗?目前甚至没有传递给方法。jsonFileStreamreadFromJARFile()

答: 暂无答案