简体   繁体   中英

Get Json File from resources folder

nowadays I'm learning Maven. I have a problem with reading json file from resources folder in my app. I've got an error message "System cannot find this file". What is more interesting, there is no problem while I'm trying to read txt file...

As you can see on image below this two files are on the same place in my app. Why my json file are not reading correctly?

在此处输入图片说明

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

在此处输入图片说明

You can use getResourceAsStream() to read resource files.

Example:

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

This assumes foo.json is

{"bar": "bat"}

and MyResult is:

public class MyResult {

    private String bar;

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

}
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)
}

Thanks for andrewJames. In my case, the json file is /src/main/resources/address.json. The class is /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;
    }
}

I'm using the community edition of IntelliJ and was able to load the json from the desired data directory. After you click run, check the target folder and you should see the target > classes > data directory - it should get automatically copied over. If the data directory is not present, trying clicking run again. For me, it didn't show up for some reason after my first run attempt.

I did not need to add resources to my pom.xml. I also tried adding directories like json and files; both worked the same as the data directory.

my gist loading json with the Gson library

I also found this article helpful forunderstanding the target directory .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM