第五次作业(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);
}
}
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();
}
}
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(); }
}
}
相关文章推荐
- 自考路之百尺竿头须进步
- 西电网络赛 - C
- Java多线程(5) interrupt
- ACM之路的开始
- 海量Web日志分析 用Hadoop提取KPI统计指标
- 西电网络赛 - B
- Linux---centos搭建git服务器
- linux文件权限详解
- Android View框架的draw机制
- CentOS7.0下用c语言编程输出mysql5.7数据库某张表中的数据到txt文件中
- 2012年 国王游戏
- [Java拾遗四]JavaWeb基础之Servlet_Request&&Response
- C++虚函数的调用过程
- Java数组操作的方法
- 西电网络赛 - A
- Qt Model/View/Delegate浅谈 - QAbstractListModel
- Mycat 感想
- MySQL数据约束
- 【leetcode】String——Roman to Integer(13)
- Android位置服务--BaiduMap的使用(2)