RandomAccessFile(随机读取文件内容的流)的应用

作者在 2010-05-09 16:44:35 发布以下内容

 //RandomAccessFile(随机读取文件内容的流)的应用
 private static File file = new File("d:/access.txt");;

 public static void main(String[] args) {
  init();// 调用静态方法 init
  count("msl", 32);
  showall();
 }

 // 判断用户是否存并传值name为这个人的名字,num为这次所得的分数
 public static void count(String name, int num) {
  try {
   RandomAccessFile raf = new RandomAccessFile(file, "rw");
   // 读取这个文件,并指定读取这个文件的方式,采用rw(即读又写)
   boolean b = false;
   while (raf.getFilePointer() < raf.length()) {
    // getFilePointer找到指定的位置,
    String name1 = raf.readUTF();
    if (name.equals(name1)) {
     raf.writeInt(num);
     b = true;
     break;
    } else {
     raf.skipBytes(4);
    }
   }
   if (!b) {
    raf.writeUTF(name);
    raf.writeInt(num);
   }
   raf.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 // 初始化文件,如果文件不存在就创建文件
 public static void init() {
  if (!file.exists()) {
   try {
    file.createNewFile();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }

 // 显示所有的信息
 public static void showall() {
  try {
   RandomAccessFile raf = new RandomAccessFile(file, "r");
   while (raf.getFilePointer() < raf.length()) {
        System.out.println(raf.readUTF());//输出数据
        System.out.println(raf.readInt());
   }
   raf.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

专业文章 | 阅读 1422 次
文章评论,共0条
游客请输入验证码
浏览275850次