如何在内部存储上编写JSON文件

时间:2016-02-11 16:14:55

标签: android

我想在内部存储上写json文件,但我无法处理它。这是我的代码:

String answers_json = data.getExtras().getString("answers");
            Log.d("****", "****************** WE HAVE ANSWERS ******************");
            Log.v("ANSWERS JSON", answers_json);
            Log.d("****", "*****************************************************");

            try {
                File file = new File (getFilesDir(),"answers.json");
                FileWriter fileWriter = new FileWriter(file);
                BufferedWriter writer = new BufferedWriter(fileWriter);
                writer.write("answers");
                writer.flush();
                writer.close()

我尝试了很多变种,但它总是以“打开失败”错误结束,或者一切都很好,我的手机上找不到文件(这意味着什么也没发生)。我身上有什么问题?

2 个答案:

答案 0 :(得分:1)

我明白了。这对我有用......

            try {
                String FILENAME = "answers.json";
                FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);
                assert answers_json != null;
                fos.write(answers_json.getBytes());
                fos.close();
            }

            catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

致以问候并感谢您的帮助。

答案 1 :(得分:-1)

这可能会对您有所帮助:

 private void downloadAndStoreJson(String url,String tag){

    JSONParser jParser = new JSONParser();
    JSONObject json = jParser.getJSONFromUrl(url);          

    String jsonString = json.toString();                
    byte[] jsonArray = jsonString.getBytes();

    File fileToSaveJson = new File("/sdcard/appData/LocalJson/",tag);



    BufferedOutputStream bos;
    try {
        bos = new BufferedOutputStream(new FileOutputStream(fileToSaveJson));
        bos.write(jsonArray);
        bos.flush();
        bos.close();

    } catch (FileNotFoundException e4) {
        // TODO Auto-generated catch block
        e4.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally {
        jsonArray=null;
        jParser=null;
        System.gc();
    }}
相关问题