我正在使用 eclipse 来读取 json 文件。我将 jsonfile 放在 src->main->java->testjson->jsonfile.json 中。现在我正在尝试读取 jsonfile。但我的程序找不到该文件。我得到的输出是“无”。这是我已经实现的代码:
JsonParser parser = new JSONParser();
try{
Object obj = parser.parse(new FileReader("jsonfile.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
}
catch(Exception e){
System.out.println("nothing");
}
最佳答案
项目中的文件称为“资源”,它将捆绑在生成的 jar
文件中。
在 maven
项目中,此类文件驻留在特殊文件夹 resources
中(如 src/main/resources/testjson/jsonfile.json
),在许多其他项目类型中,这些文件直接位于 java
文件下方。
因此您无法使用 FileReader
读取它,因为它不是常规文件,而是压缩在 jar
文件内。
您所要做的就是使用 this.getClass().getResourceAsStream("/testjson/jsonfile.json") 读取文件
。
您的解析器应该能够从InputStream
而不是Reader
读取。
如果没有,请使用具有正确编码的 InputStreamReader
(JSON 文件应该是 UTF-8,但这取决于...)
代码:
try (InputStream is = this.getClass().getResourceAsStream("/testjson/jsonfile.json"); ) {
Object obj = parser.parse(is);
} catch (Exception ex) {
System.out.println("failed to read: "+ex.getMessage());
}
如果解析器不支持InputStream
,则代码:
try (InputStream is = this.getClass().getResourceAsStream("/testjson/jsonfile.json");
Reader rd = new InputStreamReader(is, "UTF-8"); ) {
Object obj = parser.parse(rd);
} catch (Exception ex) {
System.out.println("failed to read: "+ex.getMessage());
}
关于java - java无法读取json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56076000/