使用RandomAccessFile时读取文件乱码

时间:2017-07-13 07:31:43

标签: java android java-io randomaccessfile

首先,我使用此代码在文件中写两行:

String lineSeparator = System.getProperty("line.separator", "\n");
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "test1.txt";
RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "rw");

randomAccessFile.writeUTF("aaaaaaaaaaaaaaaaaaaaa");
randomAccessFile.write(lineSeparator.getBytes());
randomAccessFile.writeUTF("bbbbbbbbbbbbbbbbbbbb");
randomAccessFile.write(lineSeparator.getBytes());

randomAccessFile.close();

写完文件后,我读到了文件:

RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
int i = 0;
String line;
while ((line = randomAccessFile.readLine()) != null) {
    Log.i("log", (i++)+" : "+line);
}
randomAccessFile.close();

但奇怪的事情发生了,每一行都以��开头,我不知道它是什么。

完整日志:

07-13 07:21:41.027 1138-1138/? I/log: 0 : ��aaaaaaaaaaaaaaaaaaaaa
07-13 07:21:41.027 1138-1138/? I/log: 1 : ��bbbbbbbbbbbbbbbbbbbb

什么是乱码字符串,是行分隔符?而且,我该如何正确阅读文件?

我尝试使用writeChars代替writeUTF,但更多的乱码会出现在日志中:

07-13 08:14:26.352 16821-16821/? I/log: 0 : ��a��a��a��a��a��a��a��a��a��a��a��a��a��a��a��a��a��a��a��a��a
07-13 08:14:26.352 16821-16821/? I/log: 1 : ��b��b��b��b��b��b��b��b��b��b��b��b��b��b��b��b��b��b��b��b

1 个答案:

答案 0 :(得分:2)

randomAccessFile.writeUTF("aaaaaaaaaaaaaaaaaaaaa");
randomAccessFile.write(lineSeparator.getBytes());
randomAccessFile.writeUTF("bbbbbbbbbbbbbbbbbbbb");
randomAccessFile.write(lineSeparator.getBytes());
randomAccessFile.close();

阅读的唯一方法是:

String aaa = randomAccessFile.readUTF();
randomAccessFile.readFully(lineSeparator.getBytes());
String bbb = randomAccessFile.readUTF();
randomAccessFile.readFully(lineSeparator.getBytes());

可以看出,写行分隔符完全是浪费时间和空间。

简而言之,writeUTF()会写入只能由readUTF()读取的数据。

参见Javadoc。