跳跃式读写文件

package demo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;

public class RandomAccessFileDemo {

	public static void main(String[] args) throws Exception {
		//跳跃式读写文件
		File file=new File("D:"+File.separator+"abc.txt");
		RandomAccessFile raf=new RandomAccessFile(file,"rw");		//读写模式
		String names[]=new String[] {"zhangsan","lisi","wangwu"};	
		int ages[]=new int[] {10,20,30};
		for(int i=0;i<3;i++) {
			raf.write(names[i].getBytes());
			raf.writeInt(ages[i]);
		}
		
		raf.seek(0);		//跳转到开头
		byte[] buf=new byte[8];
		int len=raf.read(buf);
		System.out.println("姓名:"+new String(buf,0,len));
		raf.skipBytes(10);		//跳过10个字节
		len=raf.read(buf);
		System.out.println("姓名:"+new String(buf,0,len));
		
		raf.close();
	}

}

posted @ 2022-05-14 16:02  fighterk  阅读(27)  评论(0)    收藏  举报