我有一个包含以下内容的文本文件:
Ehsan,12345,11111,1000
maryam,147258,222,5000
reza,758694,abcd,4600
Ali,564789,kfcg,7500
mohammad,658932,bnfgd,5800
zahra,758964,798564,6750
rasool,568974,457832,1400
Ahmad,785403,wasd,6900
Amir,3205809,man123,7000
Morad,1,1,8900
我阅读了所有内容RandomAccessFile
:
Account2[] members = new Account2[10];
try {
RandomAccessFile raf = new RandomAccessFile("d:\\myTxtFile.txt", "r");
raf.seek(0);
long position = raf.getFilePointer();
int counter = 0;
while(raf.length()> position){
members[counter] = new Account2(raf.readLine(), position);
position =raf.getFilePointer();
counter++;
}
} catch (Exception e) {
e.printStackTrace();
}
然后在Account2
我有一种在更改后保存文件的方法:
private long position;
public Account2(String l, long p){
super(l);
position = p;
}
public void saveFile(){
try {
RandomAccessFile raf = new RandomAccessFile("d:\\myTxtFile.txt", "rw");
raf.seek(position);
String newContents = "my new contents here";
//raf.writeChars(newContents.toString());
raf.writeUTF(newContents);
} catch (Exception e) {
e.printStackTrace();
}
但它破坏了我的文本文件并在行首添加了一些奇怪的字符并将下一行带到行尾。为什么是这样?