import java.io.*;class RandomFileTest
{
public static void main(String[] args) throws Exception
{
Student s1=new Student(1,"zhangsan",98.5);
Student s2=new Student(2,"lisi",96.5);
Student s3=new Student(3,"wangwu",78.5);
RandomAccessFile raf=new RandomAccessFile("student.txt","rw");
s1.writeStudent(raf);
s2.writeStudent(raf);
s3.writeStudent(raf);

Student s=new Student();
raf.seek(0);
for(long i=0;i<raf.length();i=raf.getFilePointer())
{
s.readStudent(raf);
System.out.println(s.num+":"+s.name+":"+s.score);
}
raf.close();
}
}class Student
{
int num;
String name;
double score;
public Student()
{
}
public Student(int num,String name,double score)
{
this.num=num;
this.name=name;
this.score=score;
}
public void writeStudent(RandomAccessFile raf) throws IOException
{
raf.writeInt(num);
raf.writeUTF(name);
raf.writeDouble(score);
}
public void readStudent(RandomAccessFile raf) throws IOException
{
num=raf.readInt();
name=raf.readUTF();
score=raf.readDouble();
}
}  
这个是一个简单的程序,没有什么大的问题,有个地方我不明白就是在自己定义的类Student中
public void writeStudent(RandomAccessFile raf) throws IOException
{
raf.writeInt(num);
raf.writeUTF(name);
raf.writeDouble(score);

对象变量没有进行初始化 (RandomAccessFile raf=new RandomAccessFile(*.txt,"rw");)
那为什么能用该类的方法 (Raf.writeInt(num);
raf.writeUTF(name);
raf.writeDouble(score);)困饶.....会的人给我解答下。

解决方案 »

  1.   

    java.io.RandomAccessFile去看看API中的这个类就知道了。对象变量没有进行初始化?我不知道LZ是什么意思。
    new RandomAccessFile("student.txt","rw"); //这不是在构造方法中初始化了么?
      

  2.   

    public void writeStudent(RandomAccessFile raf);你这里定义了方法的参数,就是说,传给这个方法的参数值就是RandomAccessFile类对象的一个实例
      

  3.   

    我的意思就是在student类中 自己写的public void writeStudent(RandomAccessFile raf)方法  在该方法体中 raf调用了RandomAccessFile类的方法 ,但是调用类方法必须是类的实例也就是new后才能用,但是这个raf为什么直接就调用了.!
      

  4.   

    public void writeStudent(RandomAccessFile raf)
    这里传入的是一个对象,然后方法体中调用的是这个对象的方法。