RamdonAccessFile 是個很好用的類,功能十分強大,可以利用它的length()和seek()方法來輕松實現文件的追加,相信我下面這個例子是很容易看懂的,先寫入十行,用length()讀出長度(以byte為單位),在用seek()移動到文件末尾,繼續添加,最後顯示記錄。
import java.io.*;
public class IOStreamDemo {
public static void main(String[] args) {
try{
RandomAccessFile rf1 = new RandomAccessFile("d:\jeru.txt","rw");
for (int i = 0; i < 10; i ++ ) {
rf1.writeBytes("xixi,this is line "+i+"
");
}
rf1.close();
int i = 0;
String record = new String();
RandomAccessFile rf2 = new RandomAccessFile("d:\jeru.txt","rw");
rf2.seek(rf2.length());
rf2.writeBytes("lala,append line"+"
");
rf2.close();
RandomAccessFile rf3 = new RandomAccessFile("d:\jeru.txt","r");
while ((record = rf3.readLine()) != null) {
i ++;
System.out.println("Value "+i+":"+record);
}
rf3.close();
}catch(Exception e){}
}
}