Java IO學習筆記(二):RandomAccessFile類

來源:互聯網
上載者:User

之前的File類只是針對檔案本身進行操作的,而如果相對檔案內容進行操作,則可以使用RandomAccessFile類,此類屬於隨即讀取類,可以隨機的讀取一個檔案中指定位置的資料。

因為在檔案中,所有得內容都是按照位元組存放的,都有固定的儲存位置。

 

建構函式:

public RandomAccessFile(File file,String mode)throws FileNotFoundException

執行個體化此類的時候需要傳遞File類。告訴程式應該操作的是哪個檔案,之後有個模式,檔案的開啟模式,常用的兩種模式:

  • r:讀
  • w:寫
  • rw:讀寫,如果使用此模式,如果檔案不存在,則會自動建立

先寫資訊:

 1 import java.io.File;
2 import java.io.IOException;
3 import java.io.RandomAccessFile;
4
5 public class Test9 {
6 public static void main(String[] args) throws IOException {
7 File f = new File("d:" + File.separator+"test.txt");
8 RandomAccessFile raf=new RandomAccessFile(f,"rw");//讀寫入模式,如果該路徑不存在會自動建立
9 String name1="jim";
10 int age1 =20;
11 String name2="Tom";
12 int age2=30;
13 raf.writeBytes(name1);
14 raf.writeInt(age1);
15 raf.writeBytes(name2);
16 raf.writeInt(age2);
17 raf.close();
18 }
19 }

然後讀檔案:

 1 import java.io.File;
2 import java.io.IOException;
3 import java.io.RandomAccessFile;
4
5 public class Test10 {
6 public static void main(String[] args) throws IOException {
7 File f = new File("d:" + File.separator+"test.txt");
8 RandomAccessFile raf=new RandomAccessFile(f,"r");//以讀模式開啟
9 raf.skipBytes(7);//跳過第一個人的資訊
10 byte[] bs=new byte[3];
11 for(int i=0;i<bs.length;i++){
12 bs[i]=raf.readByte();
13 }
14 String name2=new String(bs);
15 int age2=raf.readInt();
16 System.out.println(name2+" "+age2);
17
18 raf.seek(0);//指標回到檔案開頭,讀取第二個人的資訊
19 for(int i=0;i<bs.length;i++){
20 bs[i]=raf.readByte();
21 }
22 String name1=new String(bs);
23 int age1=raf.readInt();
24 System.out.println(name1+" "+age1);
25 }
26 }

另外:可能有的同學輸入的是中文,那麼使用getBytes()轉換,會佔3個位元組(取決你的本地編碼,如果用Eclipse可設定成UTF-8),咦?java裡面中文不是佔兩個位元組嗎?怎麼會變成3個位元組呢?其實這不是一個概念,java預設字元編碼的是unicode,確實佔兩個位元組,但是在String換轉byte[]時用的getBytes()預設用的編碼進行轉換,那麼就會佔3個位元組,unicode和UTF-8不是一個概念,仔細觀察的話會發現getBytes()方法有另外的重載getBytes("……"),例如通過getBytes("gbk"),這是轉化的中文就會變成兩位元組了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.