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();
}
}
RandomAccessFile
最新推荐文章于 2023-11-26 16:55:56 发布