日期:2014-05-20  浏览次数:20875 次

关于RandomAccessFile用法的一个小例子,可是一直抛出异常
我这个例子是想用一个RandomAccessFile的对象将Student这个类写进Student1.txt文档中,可是一直抛出异常,源代码在这里,求解啊:
import java.io.*;

public class WriteStudent1 {
public static void main(String[] args) throws IOException {
File f = new File("e:/Student1.txt");
Student[] s = new Student[3];
s[0] = new Student(18);
s[1] = new Student(19);
//Student s3 = new Student(20, "Jane");

RandomAccessFile raf = new RandomAccessFile(f, "rw");

for(int i=0; i<2; i++) {
s[i].writeStudent(raf);
}

for(int i=0; i<2; i++) {
Student stu = s[i].readStu(raf);
System.out.println(stu);
}

raf.close();
}

}

class Student {
int age;
//String name;

public Student(int age) {
this.age = age;
//this.name = name;
}

public String toString() {
return "Age: " + age; //+ "Name: " + name;
}

public void writeStudent(RandomAccessFile raf) throws IOException {
raf.writeInt(age);
//raf.writeBytes(name);
}

public Student readStu(RandomAccessFile raf) throws IOException {
int i = raf.readInt();
return new Student(i);
}
}

------解决方案--------------------
或者在两个for之间加入

raf.seek(0);

你写文件的时候,指针跟着移动的。但是读文件必须从头开始,所以指针要设为0
------解决方案--------------------
RandomAccessFile raf = new RandomAccessFile(f, "rw");

for (int i = 0; i < 2; i++)
{
s[i].writeStudent(raf);
}
raf.seek(0);

for (int i = 0; i < 2; i++)
{
Student stu = s[i].readStu(raf);
System.out.println(stu);
}

raf.close();

读的时候指针必须移到初始位置,用到seek方法,但是你必须把中间的那个raf.close()方法给删除。