【问题标题】:write and read strings to/from internal file向/从内部文件写入和读取字符串
【发布时间】:2011-05-12 20:06:13
【问题描述】:

我看到很多这样的例子:

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

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

但不是如何从内部应用程序文件中读回它们。大多数示例都假定特定的字符串长度来计算字节缓冲区,但我不知道长度是多少。有没有简单的方法可以做到这一点?我的应用最多可向文件写入 50-100 个字符串

【问题讨论】:

    标签: android string file


    【解决方案1】:

    以这种方式编写字符串不会在文件中放置任何类型的分隔符。你不知道一个字符串在哪里结束,下一个从哪里开始。这就是为什么在读回字符串时必须指定字符串的长度。

    您可以改用DataOutputStream.writeUTF()DataInputStream.readUTF(),因为这些方法会将字符串的长度放入文件中并自动读回正确数量的字符。

    在 Android 上下文中,您可以执行以下操作:

    try {
        // Write 20 Strings
        DataOutputStream out = 
                new DataOutputStream(openFileOutput(FILENAME, Context.MODE_PRIVATE));
        for (int i=0; i<20; i++) {
            out.writeUTF(Integer.toString(i));
        }
        out.close();
    
        // Read them back
        DataInputStream in = new DataInputStream(openFileInput(FILENAME));
        try {
            for (;;) {
              Log.i("Data Input Sample", in.readUTF());
            }
        } catch (EOFException e) {
            Log.i("Data Input Sample", "End of file reached");
        }
        in.close();
    } catch (IOException e) {
        Log.i("Data Input Sample", "I/O Error");
    }
    

    【讨论】:

    • 谢谢,我已经尝试过了,但由于某种原因 DataInputStream.readUTF() 只读取第一个字符串。但我可能会在那里做错事
    • 很好,它有效!非常感谢,亚历山大!我喜欢如何阅读直到文件结束 - 我正在考虑快速不要为每一行创建一个 String 对象,你也回答了我的第二个问题 :)
    猜你喜欢
    • 2012-12-31
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    相关资源
    最近更新 更多