从内部文件写入和读取字符串

时间:2010-11-19 19:35:35

标签: android string file

我看到很多例子如何写这样的String对象:

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

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

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

1 个答案:

答案 0 :(得分:14)

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

您可以使用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");
}