写入和读取字符串/从内部文件 [英] write and read strings to/from internal file

查看:132
本文介绍了写入和读取字符串/从内部文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I see a lot of examples how to write String objects like that:

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

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

但不知道如何阅读从内部应用程序文件恢复。大多数的例子假定特定字符串的长度来计算字节的缓冲区,但我不知道是什么的长度会。有一个简单的方法,这样做?我的应用程序会写入高达50-100字符串的文件

but not how to read them back from internal application file. Most of examples assume specific string length to calculate byte buffer but I do not know what the length will be. Is there an easy way to do so? My app will write up to 50-100 strings to the file

推荐答案

写作字符串这样不把任何类型的分隔符的文件中。你不知道其中一个字符串结束和下一个开始。这就是为什么你必须阅读他们回来时,指定的字符串的长度。

Writing strings this way doesn't put any sort of delimiters in the file. You don't know where one string ends and the next starts. That's why you must specify the length of the strings when reading them back.

您可以使用 DataOutputStream.writeUTF() DataInputStream.readUTF(),而不是因为这些方法把长该文件中的字符串和自动回读的字符的权数。

You can use DataOutputStream.writeUTF() and DataInputStream.readUTF() instead as these methods put the length of the strings in the file and read back the right number of characters automatically.

在一个Android环境下,你可以做这样的事情:

In an Android Context you could do something like this:

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");
}

这篇关于写入和读取字符串/从内部文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆