Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

android - write and read strings to/from internal file

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();

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...