【问题标题】:Write a List to internal storage onPause(), then read the List onResume()将 List 写入内部存储 onPause(),然后读取 List onResume()
【发布时间】:2011-06-26 06:02:52
【问题描述】:

我很困惑。阅读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();
    }

我正在尝试通过调用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 异常。如果我的术语不正确,我很抱歉,我是新手。感谢您的任何指点。

【问题讨论】:

    标签: android list storage fileinputstream fileoutputstream


    【解决方案1】:

    在您的 readFile(...) 方法中代替以下内容...

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

    试试……

    FileInputStream stream = openFileInput(path);
    

    【讨论】:

    • 你太棒了!我还必须从readFile() 方法中删除static。不过现在效果很好。 (另外我真的不知道静态和非静态的东西有什么区别,所以我只是将它们放入并在看到 eclipse 对我大喊大叫时随机删除它们。)
    • @Age:很高兴为您提供帮助。我没有发现 static 声明,但它可能仍然相关,具体取决于您的代码的其余部分。根据经验,除非您确定需要它,否则不要使用它。尝试使用 Google 搜索“Java 静态关键字”——它可能会带来一些有助于理解它的内容。
    猜你喜欢
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 2018-05-24
    相关资源
    最近更新 更多