随机文件读取流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(); } }
相关文章推荐
- RandomAccessFile
- RandomAccessFile
- Java-IO之RandomAccessFile
- IO实战-RandomAccessFile在本地实现伪断点续传
- 用RandomAccessFile实现linux tail命令效果
- Java RandomAccessFile用法(转)
- Java IO的RandomAccessFile的使用
- RandomAccessFile读取大文件时效率很低,现进行改进---BufferedRandomAccessFile
- RandomAccessFile和File的区别
- java RandomAccessFile的使用
- IO流——RandomAccessFile
- RandomAccessFile随机访问文件的读取和写入
- RandomAccessFile详解
- 黑马程序员------IO流(No.4)(打印流、序列流、管道流、RandomAccessFile、常用数据类型的操作流)
- 大文件下载之RandomAccessFile
- Java RandomAccessFile用法
- 黑马程序员----浅谈RandomAccessFile格式化数据问题和多个对象序列化存取的两个方法
- Java_RandomAccessFile和IO流
- <Java>RandomAccessFile在文件中定位写入
- Java RandomAccessFile的使用