0

目前我正在尝试保存对手机内部存储的响应。一切正常,直到我再次尝试检索数据。当我注销检索到的数据时,它只注销响应的一小部分,其余部分不存在。我试过删除文件并再次调用它,以防它使用旧文件。

保存代码

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

任何形式的建议都会很棒!

4

2 回答 2

1

原因

问题是在每次迭代中都会再次分配 line 变量

尝试这个:

 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());
于 2014-08-22T09:25:58.697 回答
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());
于 2014-08-22T09:28:11.983 回答