将文件存储到内部存储并读取它

时间:2014-04-28 22:14:06

标签: android

我要做的是将JSON文件作为字符串存储在内部存储中以便以后访问它。这背后的原因是不必在每个请求上访问服务器,因为这些数据是不变的。一旦存储一次,除非有某种更新,否则不必再次检索它。文件存储不是我以前做过的事情,我希望有人可以帮我一臂之力。我当前的代码在此行抛出一个空指针异常:

File file = new File(getFilesDir(), fileName);

我的代码:

protected String doInBackground(String[] runeId) {
        String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/rune/" +  runeId[0] + "?api_key=" + api_key;
        JSONParser jsonParser = new JSONParser();
        JSONObject runeInfo = jsonParser.getJSONFromUrl(url);
        String jsonString = runeInfo.toString();
        String fileName = "runeInfo";
        File file = new File(getFilesDir(), fileName);
        String readJson = null;

        if(!runesCached) {
            Log.d("Cache", "Caching File");
            try {

                FileOutputStream os = new FileOutputStream(file);
                os.write(jsonString.getBytes());
                os.close();
                Log.d("Cache", "Cache Complete");
                runesCached = true;
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        String name = null;
        try {
            FileInputStream fis;

            File storedRuneInfo = new File(getFilesDir(), fileName);
            fis =  new FileInputStream(storedRuneInfo);

            fis.read(readJson.getBytes());
            JSONObject storedJson = new JSONObject(readJson);

            try {
                name = storedJson.getString("name");
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return name;
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个,而不是:

File file = new File(getFilesDir().toString(), fileName);

getFilesDir()返回一个File,而不是一个String,File类构造函数将其作为参数。

getFilesDir()toString()应返回类似/data/data/com.your.app /

的内容

编辑:

这会产生同样的错误。怎么样:

try {
    FileWriter fstream;
    BufferedWriter out;

    fstream = new FileWriter(getFilesDir() + "/" + "filename");
    out = new BufferedWriter(fstream);
    out.write(jsonString.getBytes());
    out.close();

} catch (Exception e){}