java 代码
- /*RandomAccessFile
- 此类的实例支持对随机存取文件的读取和写入。随机存取文件的行为类似存储在
- 文件系统中的一个大型字节数组。存在指向该隐含数组的光标或索引,称为文件指针;
- 输入操作从文件指针开始读取字节,并随着对字节的读取而前移此文件指针。
- 如果随机存取文件以读取/写入模式创建,则输出操作也可用;输出操作从文件指
- 针开始写入字节,并随着对字节的写入而前移此文件指针。写入隐含数组的当前末
- 尾之后的输出操作导致该数组扩展。该文件指针可以通过 getFilePointer 方法
- 读取,并通过 seek 方法设置。
- 通常,如果此类中的所有读取例程在读取所需数量的字节之前已到达文件末尾,
- 则抛出 EOFException(是一种 IOException)。如果由于某些原因无法读
- 取任何字节,而不是在读取所需数量的字节之前已到达文件末尾,则抛出
- IOException,而不是 EOFException。需要特别指出的是,如果流已被关闭,
- 则可能抛出 IOException。
- */
- import java.io.*;
- public class RandomFileTest {
- public static void main(String[] args) throws Exception {
- Student st1 =new Student(1,"zhangsan",10.5);
- Student st2 =new Student(1,"lisi",20.5);
- Student st3 =new Student(3,"wangwu",30.5);
- RandomAccessFile raf = new RandomAccessFile("student.txt","rw");//读写方式打开
- st1.writeStudent(raf);//将Student st1写入文件
- st2.writeStudent(raf);
- st3.writeStudent(raf);
- Student s = new Student();
- raf.seek(0);//文件指针回到文件起始位置处
- int i=0;//测试循环次数
- for(long l=0;l<raf.length();l=raf.getFilePointer()) {
- s.readStudent(raf);//读取文件信息到s中
- System.out.println(s.num+":"+s.name+" "+s.score);
- ++i;
- }
- System.out.println("i:"+i);
- raf.close();
- }
- }
- class Student {
- int num;
- String name;
- double score;
- Student() {
- }
- public Student(int num,String name,double score) {
- this.num = num;
- this.name = name;
- this.score = score;
- }
- //往raf指向的文件中写
- public void writeStudent(RandomAccessFile raf) throws IOException {
- raf.writeInt(num);
- raf.writeUTF(name);
- raf.writeDouble(score);
- }
- // 从raf指向的文件中读
- public void readStudent(RandomAccessFile raf) throws IOException {
- num = raf.readInt();
- name = raf.readUTF();
- score = raf.readDouble();
- }
- }
- /*输出
- 1:zhangsan 10.0
- 1:lisi 20.0
- 3:wangwu 30.0
- i:3
- */
- */