write and read strings to/from internal file

前端 未结 1 820
無奈伤痛
無奈伤痛 2020-12-16 00:18

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

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

FileOutputStream fos = op         


        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 00:41

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

    0 讨论(0)
提交回复
热议问题