Java IO之RandomAccessFile类

Java IO中File类只是针对文件本身进行操作,若想要对文件内容进行操作,则可以用是RandomAccessFile类。


此类属于随机读取类,可以随机读取一个文件中指定位置的数据。


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

public class RandomAccessFileDemo01 {
	public static void main(String[] args) throws Exception{
		//写内容到文件
		String path = "d:" + File.separator + "test.txt";
		File f1 = new File(path);
		RandomAccessFile raf = null;
		raf = new RandomAccessFile(f1, "rw");
		
		String name = null;
		int age = 0;
		name = "zhangsan";
		age = 30;
		raf.writeBytes(name);
		raf.writeInt(age);
		
		name = "lisi    ";
		age = 31;
		raf.writeBytes(name);
		raf.writeInt(age);
		
		name = "wangwu  ";
		age = 32;
		raf.writeBytes(name);
		raf.writeInt(age);
		
		raf.close();
		
		
		//读取文件
		File f2 = new File(path);
		RandomAccessFile raf2 = new RandomAccessFile(f2, "r");
		
		String name2 = null;
		int age2 = 0;
		
		byte b[] = new byte[8];
		raf2.skipBytes(12);
		for(int i = 0; i < b.length; i++){
			b[i] = raf2.readByte();
		}
		name2 = new String(b);
		age2 = raf2.readInt();
		System.out.println("第二个人的信息 --> 姓名:" + name2 + ";年龄:" + age2);		
		raf2.close();
	}
}


你可能感兴趣的:(Java IO之RandomAccessFile类)