【问题标题】:Where do I have to put a json file to be available in Java? [duplicate]我必须在哪里放置一个 json 文件才能在 Java 中使用? [复制]
【发布时间】:2020-05-06 09:21:28
【问题描述】:

我有一个项目,我喜欢从 json 文件中读取数据。但是,找不到这些文件。我已经尝试过 java 目录,以及 src/main/resources。阅读我使用的文件:

InputStream is = new FileInputStream(file);

其中 file 是文件的名称,例如。 “test.json”。

是否有我需要使用的特定目录?当我使用像“c:\temp\test.json”这样的目录时,它可以工作。

对于我正在使用 IntelliJ 和 Maven 的项目。

【问题讨论】:

标签: java json


【解决方案1】:

导入以下

import java.net.URL;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;    



public static String getFileAsString(String jsonfilename) throws IOException {
        URL url = Resources.getResource(jsonfilename);
        return Resources.toString(url, Charsets.UTF_8);
    }

保留文件 src/java/资源文件

【讨论】:

    【解决方案2】:
    InputStream is = Xxx.class.getResourceAsStream("/test.json");
    

    相对于类的包文件夹的路径,或此处的绝对路径 (/...)。 在/src/main/resources下的maven。

    URL url = Yyy.class.getResource("/test.json");
    Path path = Paths.get(url.toURI());
    String json = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      相关资源
      最近更新 更多