现在我正在学习Maven。我在从我的应用程序的资源文件夹中读取 json 文件时遇到问题。我收到一条错误消息“系统找不到此文件”。更有趣的是,当我尝试读取 txt 文件时没有问题......
正如您在下面的图片中看到的,这两个文件在我的应用程序中位于同一位置。为什么我的 json 文件读取不正确?
//WORKING
String filename = "./resources/data/init_data.txt";
try (Stream<String> lines = Files.lines(Paths.get(filename))){
lines.forEach(System.out::println);
} catch (Exception e){
e.printStackTrace();
}
//NOT WORKING
Gson gson = new Gson();
filename = "./resources/data/car.json";
try (Reader reader = new FileReader(filename)){
Car car3 = gson.fromJson(reader,Car.class);
System.out.println(car3);
} catch (IOException e){
e.printStackTrace();
}
最佳答案
您可以使用 getResourceAsStream()
读取资源文件。
例子:
import java.io.Reader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.google.gson.Gson;
...
public void getJson() {
try (Reader reader = new InputStreamReader(this.getClass()
.getResourceAsStream("/foo.json"))) {
MyResult result = new Gson().fromJson(reader, MyResult.class);
System.out.println(result.getBar()); // prints "bat"
} catch (IOException e) {
e.printStackTrace();
}
}
这假设
foo.json
是{"bar": "bat"}
和
MyResult
是:public class MyResult {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
关于java - 从资源文件夹中获取 Json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60402338/