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:
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.