【发布时间】:2017-01-26 14:01:17
【问题描述】:
所以我使用 RandomAccessFile 在 java 中进行读写。但是当我将字符串写入文件时,文件的当前内容将被覆盖。这是我的代码
import java.io.RandomAccessFile;
public class hello{
public static void main(String[] args){
RandomAccessFile a;
try{
a = new RandomAccessFile("a.txt", "rw");
System.out.println(a.readLine());
a.writeUTF("another text");
}
catch(Exception e){
e.printStackTrace();
}
}
}
这是我的文件内容
101 yes no yes no
102 no no yes no
103 yes no yes no
104 no no yes no
105 no yes no no
106 yes yes yes no
但是当我运行程序时它变成了
101 yes no yes no
another text no
103 yes no yes no
104 no no yes no
105 no yes no no
106 yes yes yes no
我做错了什么?
【问题讨论】:
-
RandomAcessFile#writeUTF 在光标位置开始写入/覆盖内容,并且由于您已经使用
a.readLine()读取了一行,因此您的文件指针位于第二行的开头。完成写入/读取后,最好使用a.close()关闭文件流。
标签: java file-io randomaccessfile