Reputation: 5743
I wrote some code to read a JSON File from SD Card.
For the first I save the Path for my appfolder.
Boolean isMounted = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (isMounted) {
File Dir = new File(Environment.getExternalStorageDirectory(), "MyIdea");
//creat folder if don't exist
if (!Dir.exists()) {
if (!Dir.mkdir()) {
Log.d("MyIdea", "failed to create");
}
}
//set the absolutPath to appPathString
appDataPath = Dir.getAbsolutePath();
}
After that I put the config.json into the folder and want to read the JSON File from SD-Card with this method.
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open(appDataPath + "/config.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;
}
return json;
}
After that i want to get Data from the File
JSONObject obj = new JSONObject(loadJSONFromAsset());
But if I run the code through the Debugger I get the message on ex:
java.io.FileNotFoundException: /storage/emulated/0/MyIdea/config.json
Upvotes: 0
Views: 1583
Reputation: 6828
The file is not in your assets
folder but still you are using getAssets
. The file in the sdcard can be opened just like any normal file in java.
Try this,
public String loadJSON() {
String json = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(appDataPath + "/config.json"));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
json = buffer.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
return json;
}
Also make sure you have the following permission in Manifest.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Do not create a buffer with size same as your file size. If the file is a large file, there is a high chance that you will run into an OutOfMemoryException
.
Upvotes: 1