java - 从资源文件夹中获取 Json 文件

标签 java json maven resources

现在我正在学习Maven。我在从我的应用程序的资源文件夹中读取 json 文件时遇到问题。我收到一条错误消息“系统找不到此文件”。更有趣的是,当我尝试读取 txt 文件时没有问题......

正如您在下面的图片中看到的,这两个文件在我的应用程序中位于同一位置。为什么我的 json 文件读取不正确?

enter image description here

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

enter image description here

最佳答案

您可以使用 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/

相关文章:

java - GSS-API Java 奇怪的错误

java - 如何在 Java 中执行类型安全的 Xpath 查询?

java - 创建由 Maven 项目构建的 Artifact 列表

java - MAPSTRUCT - CustomerServiceImpl 中的字段 mapperDTO 需要类型为 'com.howtodoinjava.demo.mapper.MapperDTO' 的 bean,但无法找到

javascript - Node js 错误 : Protocol "https:" not supported. 预期为 "http:"

java - 找不到包 org.springframework.web.servlet

java - 单击边框时 JComboBox 弹出窗口立即出现和隐藏(糟糕的用户体验)

java - 为什么我应该使用单独的线程在 JAVA 中显示 GUI

android - 在android中上传到服务器时获取java.lang.IllegalArgumentException

json - 将节点Filebeat接收到Elasticsearch