RandomAccessFile类实现随机读写文件

 java.io.RandomAccessFile类能够实现对文件内的随机位置进行读写操作。通过下面的一个实例来进行了解。
实例:
public class RandomAccessFileDemo03 {
public static void main(String[] args) throws IOException{
File f1=new File("e:"+File.separator+"ioString.dat");
RandomAccessFile raf=new RandomAccessFile(f1,"rw");//没有则创建
String name=null;//姓名
int age=0;//年龄
String phoneNumber=null;//电话号码
//每个人的信息用26个字节来储存
name="tangtianyun";//姓名占11个字节,不足11字节用空格补足
age=22;//int型的年龄占4个字节
phoneNumber="05718839476";//电话号码占11字节,不足11字节用空格补足
raf.writeBytes(name);
raf.writeInt(age);
raf.writeBytes(phoneNumber);
name="heyili     ";
age=23;
phoneNumber="13527971631";
raf.writeBytes(name);
raf.writeInt(age);
//raf.writeBytes(phoneNumber);//这种方式比较简便,下面的方式会复杂些。
byte[] b=phoneNumber.getBytes();//通过字符串返回byte数组
for(int i=0;i<b.length;i++){
raf.writeByte(b[i]);
}
raf.close();//写入操作完成。文件必须关闭。
//下面进行读取操作
File f2=new File("e:"+File.separator+"ioString.dat");
RandomAccessFile raf2=new RandomAccessFile(f2,"r");//r表示模式为读
String readName=null;
int readAge=0;
String readPhoneNumber=null;
//假设先读取第2个人的信息
raf2.skipBytes(1*26);//跳过26个字节,即跳过第1个人的信息
byte[] bName=new byte[11];
for(int i=0;i<11;i++){
//每次读取1个字节,循环11次将储存的名字信息放入byte数组
bName[i]=raf2.readByte();
}
readName=new String(bName);//将byte数组新构造一个String字符串
readAge=raf2.readInt();//每次读取4个字节的int数据
byte[] bPhoneNumber=new byte[11];
for(int i=0;i<11;i++){
bPhoneNumber[i]=raf2.readByte();
}
readPhoneNumber=new String(bPhoneNumber);
System.out.println("姓名:"+readName+",年龄:"+readAge+",电话号码:"+readPhoneNumber);
//假设再读取第1个人的信息
raf2.seek(0);//文件指针回到第1个字节前
bName=new byte[11];
for(int i=0;i<11;i++){
bName[i]=raf2.readByte();
}
readName=new String(bName);
readAge=raf2.readInt();
bPhoneNumber=new byte[11];
for(int i=0;i<11;i++){
bPhoneNumber[i]=raf2.readByte();
}
readPhoneNumber=new String(bPhoneNumber);
System.out.println("姓名:"+readName+",年龄:"+readAge+",电话号码:"+readPhoneNumber);
raf2.close();
}
}
使用RandomAccessFile进行文件的随机读写操作,必须要规划好每个内容储存所需要的字节数,因此比较麻烦。也正是因为这样的原因,才是它拥有了随机读写的特性。这说明 付出总有回报
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值