将列表写入内部存储onPause(),然后读取List onResume()

时间:2011-06-25 21:47:02

标签: android list storage fileinputstream fileoutputstream

我很困惑。阅读this thread后,我正在尝试将列表写入内部存储onPause(),然后阅读列表onResume()。仅出于测试目的,我正在尝试编写一个简单的字符串,如示例所示。我有这个写:

    String FILENAME = "hello_file";
    String string = "hello world!";

    FileOutputStream fos = null;
    try {
        fos = openFileOutput(FILENAME, Context. MODE_WORLD_READABLE);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        fos.write(string.getBytes());
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        fos.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

我正试图通过调用:{/ p>在onResume()中阅读它

    try {
            resultText01.setText(readFile("hello_file"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resultText01.setText("exception, what went wrong? why doesn't this text say hello world!?");
        }

当然使用它:

private static String readFile(String path) throws IOException {
      FileInputStream stream = new FileInputStream(new File(path));
      try {
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        /* Instead of using default, pass in a decoder. */
        return Charset.defaultCharset().decode(bb).toString();
      }
      finally {
        stream.close();
      }
    }

由于某种原因,resultText01.setText(...)未设置为"hello world!",而是调用catch异常。如果我的行话不正确,我很抱歉,我是新手。谢谢你的任何指示。

1 个答案:

答案 0 :(得分:2)

而不是readFile(...)方法中的以下内容......

FileInputStream stream = new FileInputStream(new File(path));

...试

FileInputStream stream = openFileInput(path);