RandomAccessFile

package com.kilophone.classcontent;

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

class Person {

	private String name;
	private int age;

	public Person() {
	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public Person(RandomAccessFile raf) {
		try {
			this.name = raf.readUTF();
			this.age = raf.readInt();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void writeMsg(RandomAccessFile raf) {
		try {
			raf.writeUTF(this.name);
			raf.writeInt(this.age);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}

	/**
	 * @param age
	 *            the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
}

/**
 * 练习:创建一个Person类,name,age两个属性,利用随机读取文件类,实例化3个人,将此3个人的信息,写入本地文件中,再读取出来。
 * 
 * @author Administrator
 * 
 */
public class TestRandomAccessFile {

	public static void getInstance() {
		Person p1 = new Person("Devin", 23);
		Person p2 = new Person("Devin", 23);
		Person p3 = new Person("Devin", 23);
		File f = new File("person.txt");
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(f, "rw");
			p1.writeMsg(raf);
			p2.writeMsg(raf);
			p3.writeMsg(raf);
			// 设置到此文件开头测量到的文件指针偏移量
			raf.seek(0);
			for (int i = 0; i < f.length(); i = (int) raf.getFilePointer()) {
				System.out.println("到此文件开头的偏移量(以字节为单位):" + i);
				Person p = new Person(raf);
				System.out.println(p);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		getInstance();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值