RandomAccessFile是Java输入、输出流体系中功能最 强大的文件内容访问类,它提供了众多方法来访问文件内容,它既可以读取文件内容,也可以向文件输出数据。与普通的输入输出流不同的 是,RandomAccessFile支持 随机访问 的方式,程序可以直接跳转到任意地方来读取数据。
RandomAccessFile对象也包含一个记录指针,用以标识当前读写处的位置,当程序新创建一个RandomAccessFile对象时,该对象 的文件记录指针位于文件头(也就是0处),当读、写n个字节后,文件记录指针将会向后移动n个字节。
RandomAccessFile可以自由移动该记录指针,既可以向前移动,也可以向后移动。RandomAccessFile包含了如下两个方法来操作 文件记录指针:
long getFilePointer( ): 返回文件记录指针的当前位置。
Void seek(long pos): 将文件记录指针定位到pos位置。
示例:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileTest {
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile("F:\workspace1\RandomAccessFileTest\src\RandomAccessFileTest.java", "r");
System.out.println("RandomAccessFile文件指针的初始位置:" + raf.getFilePointer());
raf.seek(300);
byte[] bbuf = new byte[1024];
int hasRead = 0;
while((hasRead = raf.read(bbuf)) > 0){
System.out.println(new String(bbuf, 0, hasRead));
}
raf.close();
}
}