您的位置:首页 > 其它

随机文件读取流RandomAccessFile

2010-08-17 19:46 239 查看
package com.io;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Serializable;
public final class Student implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int num;
private String name;
private transient double score;
public Student() {
}
public Student(int num, String name, double score) {
super();
this.num = num;
this.name = name;
this.score = score;
}
@Override
public String toString() {
return num + ":" + name + ":" + score;
}
public void writeStudent(RandomAccessFile raf) throws IOException {
raf.writeInt(num);
raf.writeUTF(name);
raf.writeDouble(score);
}
public void readStudent(RandomAccessFile raf) throws IOException {
num = raf.readInt();
name = raf.readUTF();
score = raf.readDouble();
}
/*private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.writeInt(num);
out.writeUTF(name);
// 证实是否真的调用了该方法
System.out.println("writeObject()");
}
private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundException {
num = in.readInt();
name = in.readUTF();
// 证实是否真的调用了该方法
System.out.println("readObject()");
}*/
}


package com.io;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomFileTest {
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile("G:/root/a.txt", "rw");
Student s1 = new Student(10, "张三", 50);
Student s2 = new Student(21, "李四", 60);
Student s3 = new Student(34, "王五", 70);
Student s4 = new Student(28, "马六", 80);
System.out.println("raf.getFilePointer()=" + raf.getFilePointer());// 0
s1.writeStudent(raf);
System.out.println("raf.getFilePointer()=" + raf.getFilePointer());// 20
s2.writeStudent(raf);
System.out.println("raf.getFilePointer()=" + raf.getFilePointer());// 40
s3.writeStudent(raf);
System.out.println("raf.getFilePointer()=" + raf.getFilePointer());// 60
s4.writeStudent(raf);
System.out.println("raf.getFilePointer()=" + raf.getFilePointer());// 80
// 读取数据
Student s = new Student();
raf.seek(0);// 从文件开头以字节为单位测量的偏移量位置,在该位置设置文件指针。
for (long i = 0; i < raf.length(); i = raf.getFilePointer()) {
s.readStudent(raf);// 将学生信息从文件当中读取出来。
System.out.println(s);
}
raf.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: