RandomAccessFile实例化时,需要设置读写模式
示例:复制文件
@Test
public void test16() throws IOException {
RandomAccessFile rafR = new RandomAccessFile("FLAMING MOUNTAIN.JPG", "r");
RandomAccessFile rafW = new RandomAccessFile("FLAMING MOUNTAIN2.JPG", "rw"); byte[] buffer = new byte[1024];
int len;
while ((len = rafR.read(buffer)) != -1){
rafW.write(buffer, 0, len);
} rafW.close();
rafR.close();
}
RandomAccessFile写入数据的特点:从头开始逐个覆盖原文件的内容
@Test
public void test17() throws IOException {
RandomAccessFile rafW = new RandomAccessFile("hello.txt", "rw");
//自动创建文件,逐个覆盖原有文件内容
rafW.write("xyz".getBytes());
rafW.close();
}
原hello.txt中的内容为:abcdefghijklmn
写入xyz后,文件内容为:xyzdefghijklmn