刚学JAVA,代码不是那么完善,参考下吧
//RandomFileTest.java
import java.io.*;
public class RandomFileTest
{
public static void main(String[] args) throws Exception
{
Student s1=new Student(1,"Mrk",18);
Student s2=new Student(2,"Rose",19);
Student s3=new Student(3,"jak",17);
RandomAccessFile raf=new RandomAccessFile("student.txt","rw");
s1.writeStudent(raf);
s2.writeStudent(raf);
s3.writeStudent(raf);
Student s=new Student();
raf.seek(0);
s.readStudent(raf);
s.readStudent(raf);
System.out.println(s.num+"name:"+s.name+" age:"+s.age);
raf.seek(0);
s.readStudent(raf);
System.out.println(s.num+"name:"+s.name+" age:"+s.age);
s.readStudent(raf);
s.readStudent(raf);
System.out.println(s.num+"name:"+s.name+" age:"+s.age);
raf.close();
}
}
class Student
{
int num;
String name;
int age;
public Student()
{
}
public Student(int num,String name,int age)
{
this.num=num;
this.name=name;
this.age=age;
}
public void writeStudent(RandomAccessFile raf) throws IOException
{
raf.writeInt(num);
raf.writeUTF(name);
raf.writeInt(age);
}
public void readStudent(RandomAccessFile raf) throws IOException
{
num=raf.readInt();
name=raf.readUTF();
age=raf.readInt();
}
}