package com.hp;
import java.io.RandomAccessFile;
public class RandomAcessTest {
public static void main(String[] args) {
try {
RandomAccessFile raf = new RandomAccessFile("2.txt","rw");
Student s1= new Student(1,"hp",99.5);
Student s2= new Student(1,"lp",99.5);
//写入2.txt文件中
s1.write(raf);
s2.write(raf);
//将文件指针重新放回开始处
raf.seek(0);
Student s= new Student();
//raf.length表示文件的长度,raf.getFilePointer()表示文件的位置
for(long i=0;i<raf.length();i=raf.getFilePointer()){
s.read(raf);
System.out.println("id="+s.id);
System.out.println("name="+s.name);
System.out.println("score="+s.score);
}
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Student{
int id;
String name;
double score;
public Student(){
}
public Student(int id,String name,double score){
this.id=id;
this.name=name;
this.score=score;
}
public void write(RandomAccessFile raf){
try{
raf.writeInt(id);
raf.writeUTF(name);
raf.writeDouble(score);
}catch(Exception e){
e.printStackTrace();
}
}
public void read(RandomAccessFile raf){
try{
id=raf.readInt();
name= raf.readUTF();
score=raf.readDouble();
}catch(Exception e){
e.printStackTrace();
}
}
}