简体   繁体   中英

FileNotFoundException in the onCreate() method

I keep receiving the FileNotFoundException error when trying to load my file into a JSONReader using an InputStream within my onCreate method.

I've tested this code in a simple Java program and it seems to work fine and also reads the JSON file too. However, within Android Studio I keep receiving the FileNotFoundException .

Am I referencing the location of the file incorrectly?

This is my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    List<String> linksList = new ArrayList<>();

    try {
        JsonReader reader = null;
        reader = new JsonReader(new FileReader("/assets/test.json"));
        reader.beginArray();

        while (reader.hasNext()) {

            String value = reader.nextString();
            linksList.add(value);
        }

        reader.endArray();
        reader.close();
    } catch (FileNotFoundException fnfe) {

        fnfe.printStackTrace();

    } catch (IOException ioe) {

        ioe.printStackTrace();
    }
}

Here is the Log -

12-27 11:56:11.342 20703-20703/com.adam.jsonreader W/System.err: java.io.FileNotFoundException: /assets/test.json (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)
    at java.io.FileInputStream.<init>(FileInputStream.java:99)
12-27 11:56:11.343 20703-20703/com.adam.jsonreader W/System.err:     at java.io.FileReader.<init>(FileReader.java:58)
        at com.adamkhora.jsonreader.HomeActivity.onCreate(HomeActivity.java:43)

Here is my project structure:

project_structure

instead of new FileReader("/assets/test.json") ,

use

new BufferedReader(new InputStreamReader(getAssets().open("test.json"), StandardCharsets.UTF_8)); 

You need to use the getAssets() method to use assets in android.

Just use below snippet by giving file name

 try {
        InputStream is = context.getAssets().open("test.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");

    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }

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