您的位置:首页 > 其它

第五次作业(1)

2016-04-17 21:51 429 查看
使用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 + "\trecord:" + times);
}
raf.close();
}catch(Exception e){
e.printStackTrace();
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: