保存到Android内部存储

时间:2014-08-22 09:18:47

标签: java android fileinputstream internal-storage

目前我正在尝试保存对手机内部存储空间的响应。一切正常,直到我再次尝试检索数据。当我注销检索到的数据时,它只会记录响应的一小部分,其余部分不存在。我已经尝试删除该文件并再次调用它,只是因为它使用旧文件。

保存代码

try {
     String response = apiResponse.getRawResponse();
     Log.e("Response", response);

     FileOutputStream userInfo = openFileOutput("personal_profile", MODE_PRIVATE);
     userInfo.write(response.getBytes());
     userInfo.close();

} catch (Exception e) {
    e.printStackTrace();

检索代码

 String response = "";

    try {
        FileInputStream fis = getActivity().openFileInput("personal_profile");
        DataInputStream isr = new DataInputStream(fis);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        line = response;

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.e("Saved File", response);

任何建议都会很棒!

2 个答案:

答案 0 :(得分:1)

原因

问题是行变量在每次迭代中再次分配

试试这个:

 String response = "";

try {
    FileInputStream fis = getActivity().openFileInput("personal_profile");
    DataInputStream isr = new DataInputStream(fis);
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        sb.append(line);
    }
    line = response;

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

更改最后一行

Log.e("Saved File", sb.toString());

答案 1 :(得分:1)

你的AndroidManifest.xml文件中有这个吗?

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

此外,此链接包含有关读取和写入文件的所有信息:

http://www.anddev.org/working_with_files-t115.html


<强> 代码 ::

  String response = "";

    try {
        FileInputStream fis = getActivity().openFileInput("personal_profile");
        DataInputStream isr = new DataInputStream(fis);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        line = response;

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.e("Saved File", sb.toString());