0
行我有這個內容的文本文件:替換的RandomAccessFile
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();
}
但它破壞我的文本文件並添加一些奇怪的charac在線的頭部,並將下一條線線尾。爲什麼是這樣?
**從不**有空的catch語句。誰知道你錯過了什麼例外。請添加一個'e.printStacktrace()'並檢查沒有打印。 –
我加了,但問題不在這裏 – Ehsan
super(l)做了什麼?父類是哪一類?你在哪裏調用saveFile()?你爲什麼要寫回相同的文件,而不是單獨的文件? – tuxdna