public void test() throws Exception{
File file = new File("c:/test.log");
RandomAccessFile rf = new RandomAccessFile(file, "rw");
long fileLength = rf.length();
// 将本件指针移到文本末尾
rf.seek(fileLength);
// 文本文件追加文本,换行符
rf.writeBytes("11111/n");
// rf.writeBytes("1111 /r/n")
rf.close();
}
// rf.writeBytes("11111/n");
程序执行上述语句:
在文本文件中有很多小黑块,因为在这个文件里面的换行标志只有一个字符,
也就是ASCII码的10,而在Windows中,换行是采用两个字符表示的,即回车加换行,也就是ASCII码的13和10。
当打开这样的文件时,
由于在这个文件当中只有换行,没有回车,所以记事本程序就把它解析成了小黑块。
解决办法:
System.out.println(System.getProperty("line.separator").length());// 2
String str = System.getProperty("line.separator");
for(int i=0;i<str.length();i++)
// 打印 ASCII 码
System.out.print((int)str.charAt(i)+" "); // 13 10
System.out.println();
---------------------------------------------
long fileLength = rf.length();
String lineSeparator = System.getProperty("line.separator");
rf.writeBytes("11111"+lineSeparator);
第一次执行 fileLength == 0
第二次执行 fileLength == 7 // 11111 + "/r/n"
---------------------------------------------------------------------
第三次执行 fileLength == 14
在 java 中 System.getProperty("line.separator").length() == 2
将字符写入文本文件而已