Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 811
mishkin Avatar asked Nov 19 '10 19:11

mishkin


1 Answers

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");
}
like image 69
Alex Jasmin Avatar answered Nov 07 '22 13:11

Alex Jasmin