RandomAccessFile

RandomAccessFile类 支持"随机访问"
文件可以不用从头开始访问,可以选择开始访问的位置。
有可以指示读取位置的文件指示器、游标。

            ↓可以选择位置
#########################

可以直接跳过前面的数据流,再开始读取。
文件记录采用等长记录格式,每一条记录都是一样长的,每条记录分成若干字段,
记录长度相等使文件可以跳转
可以指定读写方式。


String.substring(0,8) 获取前8个字符;   “/u0000”为 空字符串
注意写入时不同的对象所占用的字符大小不同,读取时根据字符调整指针位置

注意write 与 read方法对应使用

测试结果:**************************************
赵钱孙     :320
tom Gree:21
OK      :23
*************************************************

代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;

public class TestRandomAccessFile {

 public static void main(String[] args) throws Exception{
  Student s1 = new Student("tom Green",21);
  Student s2 = new Student("赵钱孙",320);
  Student s3 = new Student("OK",23);
  
  File f = new File("testRandomFile.txt");
  RandomAccessFile raf;  
  raf = new RandomAccessFile(f,"rw");  
  raf.writeChars(s1.name);
  raf.writeInt(s1.age);
  raf.writeChars(s2.name);
  raf.writeInt(s2.age);
  raf.writeChars(s3.name);
  raf.writeInt(s3.age);

  RandomAccessFile raf1 = new RandomAccessFile(f,"r");
  raf1.skipBytes(20);
  String str = "";
  for(int i=0;i<Student.LEN;i++){
   str += raf1.readChar();
  }
  System.out.print(str+":");
  int temp = raf1.readInt();
  System.out.println(temp);
  
  str = "";
  raf1.seek(0);
  for(int i=0;i<Student.LEN;i++){
   str += raf1.readChar();
  }
  System.out.print(str+":");
  temp = raf1.readInt();
  System.out.println(temp);
  
  
  str = "";
  raf1.skipBytes(20);
  for(int i=0;i<Student.LEN;i++){
   str += raf1.readChar();
  }
  System.out.print(str+":");
  temp = raf1.readInt();
  System.out.println(temp);
 }
}


public class Student {
 String name = null;
 int age = 0;
 public static final int LEN = 8;
 public Student(String name, int age) {
  if(name.length()>LEN){
   name = name.substring(0, 8);
  }
  else {
   while(name.length()<LEN){
    name += " ";
   }
  }
  this.name = name;
  this.age = age;
 }
 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值