从资源文件夹获取Json文件

5

我现在正在学习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

4个回答

5
您可以使用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;
    }

}

2
感谢andrewJames。 在我的情况下,json文件位于/src/main/resources/address.json。 类是/src/main/java/com.xxx.address.AddressUtils.java。
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;    
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
//gson 2.8.6
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class JsonResourceUtils {
    private static final Log log = LogFactory.getLog("address");
    public static JsonArray jsonArray = null;

    public static void main(String[] args) {
        System.out.println("Hello World!");
        getAddresses();
    }

    public static JsonArray getAddresses() {
        if (jsonArray != null) {
            return jsonArray;
        }
        try (Reader reader = new InputStreamReader(JsonResourceUtils.class.getResourceAsStream("/address.json"))) {
            JsonElement jsonElement = JsonParser.parseReader(reader);//gson 2.8.6
            jsonArray = jsonElement.getAsJsonArray();
            log.info("address.json read success,length:" + jsonArray.size());
            reader.close();
            for (JsonElement jeProvince : jsonArray) {
                JsonObject joProvince = jeProvince.getAsJsonObject();
                String name = joProvince.get("name").toString()
                xxx
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

String name = joProvince.get("name").toString() the right way is joProvince.get("name").getAsString() - hatanooh

1
我正在使用 IntelliJ 的社区版,并且能够通过 Maven 从所需的数据目录加载 JSON。
点击运行后,检查目标文件夹,您应该会看到目标>类>数据目录——它应该会自动复制过去。如果数据目录不存在,请尝试再次点击运行。对我来说,在第一次运行尝试后,由于某种原因它没有出现。
我不需要在我的 pom.xml 中添加资源。我还尝试添加了像 json 和 files 这样的目录;它们与数据目录的效果相同。 我的 gist 加载 Gson 库的 json 我还发现这篇文章对理解目标目录很有帮助。

0
fun getStringFromJsonFile(context: Context, fileId: Int): String {
    val inputStream: InputStream = context.resources.openRawResource(fileId)
    val writer: Writer = StringWriter()
    val buffer = CharArray(1024)
    try {
        val reader: Reader = BufferedReader(InputStreamReader(inputStream, "UTF-8"))
        var n = 0
        while (reader.read(buffer).also { n = it } != -1) {
            writer.write(buffer, 0, n)
        }
        return writer.toString()
    } catch (error: Exception) {
        Log.d(AppData.TAG, "Error : ${error.printStackTrace()}")
    } finally {
        inputStream.close()
    }

    return ""
}

//call method
val paymentJsonArr = JSONArray(getStringFromJsonFile(context, R.raw.payment_type))

//use data
for (i in 0 until paymentJsonArr.length()) {
    val jsonObject = paymentJsonArr.getJSONObject(i)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接