关于RandomAccessFile用法的一个小例子,可是一直抛出异常

rambler漫步 2012-05-23 08:10:11
我这个例子是想用一个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);
}
}
...全文
204 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
rambler漫步 2012-05-25
  • 打赏
  • 举报
回复
感谢楼上各位,明白了!!!!!!!!!!!!
xlhb 2012-05-23
  • 打赏
  • 举报
回复
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()方法给删除。
FFF9527 2012-05-23
  • 打赏
  • 举报
回复
或者在两个for之间加入

raf.seek(0);

你写文件的时候,指针跟着移动的。但是读文件必须从头开始,所以指针要设为0
FFF9527 2012-05-23
  • 打赏
  • 举报
回复

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);
}

raf.close();

RandomAccessFile raf01 = new RandomAccessFile(f, "rw");
for (int i = 0; i < 2; i++)
{
Student stu = s[i].readStu(raf01);
System.out.println(stu);
}

raf01.close();
}


以上代码是很不规范的,流必须在用try-finally 包裹 最后在finally 中将流关闭

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧