我这个例子是想用一个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);
}
}
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);
}
}
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 中将流关闭
{
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()方法给删除。