RandomAccessFileDemo随机读取文件,实现了DataInput和DataOutput接口,能够读入和写出文件。 该类实例需要两个参数:一个文件或文件路径,二个是mode访问模式,r表示读,rw表示读+写。
getFilePointer() 获取文件指针,返回一个long类型文件指针所在位置。
seek(fp) 设置文件指针位置。
package io.test6; import java.io.File; import java.io.RandomAccessFile; /** * @author yf **/ public class RandomAccessFileDemo { public static void main(String[] args) throws Exception { File file = new File("test6/out.txt"); // System.out.println(RandomMode.R); // write(file); read(file); } private static void read(File file) throws Exception { RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); //randomAccessFile.seek(1);//直接移动文件指针,指针从1开始,每个字节数量为1 long filePointer = randomAccessFile.getFilePointer(); System.out.println("文件指针位置:" + filePointer); byte b = randomAccessFile.readByte(); System.out.println(b); long filePointer2 = randomAccessFile.getFilePointer(); System.out.println("文件指针位置:" + filePointer2); byte c = randomAccessFile.readByte(); System.out.println(c); randomAccessFile.close(); } private static void write(File file) throws Exception { RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); randomAccessFile.writeByte(65); randomAccessFile.writeByte(66); randomAccessFile.close(); } }