閱讀131 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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進行文件的隨機讀寫操作,必須要規劃好每個內容儲存所需要的字節數,因此比較麻煩。也正是因為這樣的原因,才是它擁有了隨機讀寫的特性。這說明付出總有回報

最後更新:2017-04-02 06:52:14

  上一篇:go 馬士兵 正則表達式的學習(上)
  下一篇:go java.lang.Integer.toHexString(b[n] &amp; 0XFF)中0XFF使用