work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java IO系统--RandomAccessFile

Posted on 2019-05-26 21:18  work hard work smart  阅读(157)  评论(0编辑  收藏  举报

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”,文件可读不可写