代码之家  ›  专栏  ›  技术社区  ›  mishkin

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

  •  12
  • mishkin  · 技术社区  · 15 年前

    我看到很多这样的字符串对象的例子:

    String FILENAME = "hello_file";
    String string = "hello world!";
    
    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    fos.write(string.getBytes());
    fos.close();
    

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

    1 回复  |  直到 15 年前
        1
  •  14
  •   Alex Jasmin    15 年前

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

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