使用RandomAccessFile类实现游戏中记录打破记录的玩家信息和成绩的功能
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class test{
private File file;
public static void main(String[] args){
TestRandomAccessFile traf = new TestRandomAccessFile();
traf.init();
traf.record("Adom",80);
traf.listAllRecords();
}
public void record(String record_breaker, int times){
try{
RandomAccessFile raf = new RandomAccessFile(file,"rw");
boolean flag = false;
while(raf.getFilePointer() < raf.length()){
String name = raf.readUTF();
long prior = raf.getFilePointer();
if (record_breaker.equalsIgnoreCase(name)) {
flag = true;
//比较传递进来的数与之前数的大小
if (raf.readInt() < times) {
//利用seek()方法跳转到prior的位置
raf.seek(prior);
raf.writeInt(times);
break;
}
} else {
raf.skipBytes(4);
}
}
if(!flag){
raf.writeUTF(record_breaker);
raf.writeInt(times);
}
raf.close();
}catch(Exception e){
e.printStackTrace();
}
}
public void init(){
if(file == null){
file = new File("record.txt");
try{
file.createNewFile();
}catch(IOException e){
e.printStackTrace();
}
}
}
public void listAllRecords(){
try{
RandomAccessFile raf = new RandomAccessFile(file,"r");
while(raf.getFilePointer() < raf.length()){
String name = raf.readUTF();
int times = raf.readInt();
System.out.println("name:" + name + " record:" + times);
}
raf.close();
}catch(Exception e){
e.printStackTrace();
}
}
}