以这种方式编写字符串不会在文件中放入任何类型的分隔符。你不知道一根线在哪里结束,另一根线在哪里开始。这就是为什么在读取字符串时必须指定字符串的长度。
你可以用
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");
}