通过读取JSON文件

时间:2016-11-02 13:52:35

标签: android json filenotfoundexception

我写了一些代码来从SD卡读取JSON文件。

首先,我为我的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();
    }

之后我将config.json放入该文件夹,并希望使用此方法从SD卡读取JSON文件。

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;

}

之后我想从文件中获取数据

JSONObject obj = new JSONObject(loadJSONFromAsset());

但是如果我通过调试器运行代码,我会在ex:

上收到消息
java.io.FileNotFoundException: /storage/emulated/0/MyIdea/config.json

1 个答案:

答案 0 :(得分:1)

该文件不在assets文件夹中,但您仍在使用getAssets。 sdcard中的文件可以像java中的任何普通文件一样打开。

试试这个,

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

另外请确保您在Manifest中拥有以下权限。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

不要创建大小与文件大小相同的缓冲区。如果文件是大文件,则很可能会遇到OutOfMemoryException

相关问题