读取 JSON 文件时未找到文件异常

File not found Exception by reading a JSON File

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

首先,我为我的应用程序文件夹保存了路径。

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

该文件不在您的 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;
}

还要确保您在清单中具有以下权限。

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

不要创建大小与您的文件大小相同的缓冲区。如果文件是一个大文件,你很有可能 运行 变成 OutOfMemoryException.