Java RandomAccessFile的使用

public class FileDemo 
{
public static void main(String[] args) throws Exception
{
Student stu1 = new Student(1,"chichao");
Student stu2 = new Student(1,"caijing");
RandomAccessFile ref = new RandomAccessFile("D:"+File.separator+"test"+File.separator+"hello.txt","rw");//提供了对文件的读和写
stu1.writeInfo(ref);
stu2.writeInfo(ref);
Student stu3 = new Student();
ref.seek(0);//进行写操作之后,指针已经被移到了末尾,在进行读之前,要先把指针重新置到开头
for(long i=0;i<ref.length();i=ref.getFilePointer())//获取下一个要读写的位置
{
stu3.readInfo(ref);
System.out.println(stu3.name+" "+stu3.num);
}
ref.close();
}
}

 

 

class Student 
{
int num;
String name;
public Student()
{

}
public Student(int num,String name)
{
this.num = num;
this.name = name;
}

public void writeInfo(RandomAccessFile ref) throws IOException
{
ref.writeInt(num);
ref.writeUTF(name);//向输出流中写入字符串,并在字符串的开始位置开辟两个字节用来存放该字符串字节的长度
}

public void readInfo(RandomAccessFile ref) throws IOException
{
num = ref.readInt();
name = ref.readUTF();
}
}



 



posted @ 2011-11-23 10:28  xiao秋  阅读(446)  评论(0编辑  收藏  举报