Java IO系统--RandomAccessFile

RandomAccessFile 实现了DataOutput接口和DataInput接口。父类是Object,不继承任何的InputStream和OutStram。

public class RandomAccessFile implements DataOutput, DataInput, Closeable{
...
}

代码例子

定义一个Person类

class Person{
	int id;
	String name;
	
	double height;
	
	
	
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getHeight() {
		return height;
	}

	public void setHeight(double height) {
		this.height = height;
	}

	public Person() {
		
	}

	public Person(int id, String name, double height) {
		
		this.id = id;
		this.name = name;
		this.height = height;
	}
	
	public void write(RandomAccessFile raf) throws Exception{
		raf.writeInt(this.id);
		raf.writeUTF(this.name);
		raf.writeDouble(this.height);
	}
	
	public void read(RandomAccessFile raf)throws Exception{
		this.id = raf.readInt();
		this.name = raf.readUTF();
		this.height = raf.readDouble();
	}
	
	
}

  

RandomAccessFile 使用

public class RandomAccessFile1 {

	public static void main(String[] args) throws Exception {
		Person p = new Person(1,"Tom", 1.8);
		RandomAccessFile raf = new RandomAccessFile("D:/temp/randomAccessFile.txt", "rw");
		p.write(raf);
		
		
		Person p2 = new Person();
		//让读的位置重回到文件开头
		raf.seek(0);
		p2.read(raf);
		
		System.out.println(p2.getId() +" " + p2.getName() +" " +p2.getHeight());
		
	
	}
}

  

“rw”,既能读又能写

“r”,文件可读不可写

原文地址:https://www.cnblogs.com/linlf03/p/10927647.html