java RandomAccessFile類(隨機訪問檔案)

劍握在手發表於2013-11-21

該類可以實現對同一個檔案的讀寫操作,與其他IO流不同的是可以指定讀寫指標的腳標(seek),有跳過指定個數字節(skipBytes)操作。

另外該類也可用於斷點續傳。

簡單示例如下:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileDemo {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {

  /*
   * RandomAccessFile
   * 一看這個類名字,糾結。不是io體系中的子類。
   *
   * 特點:
   * 1,該物件即能讀,又能寫。
   * 2,該物件內部維護了一個byte陣列,並通過指標可以運算元組中的元素,
   * 3,可以通過getFilePointer方法獲取指標的位置,和通過seek方法設定指標的位置。
   * 4,其實該物件就是將位元組輸入流和輸出流進行了封裝。
   * 5,該物件的源或者目的只能是檔案。通過建構函式就可以看出。
   *
   *
   */
  
//  writeFile();
//  readFile();
  randomWrite();
 }
 
 public static void randomWrite() throws IOException{
  RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "rw");
  
  //往指定位置寫入資料。
  raf.seek(3*8);
  
  raf.write("哈哈".getBytes());
  raf.writeInt(108);
  
  raf.close();
 }
 
 
 public static void readFile() throws IOException {
  
  RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "r");
  
  //通過seek設定指標的位置。
  raf.seek(1*8);//隨機的讀取。只要指定指標的位置即可。
  
  byte[] buf = new byte[4];
  raf.read(buf);
  
  String name = new String(buf);
  
  int age = raf.readInt();
  
  System.out.println("name="+name);
  System.out.println("age="+age);
  
  System.out.println("pos:"+raf.getFilePointer());
  
  raf.close();
  
  
 }

 //使用RandomAccessFile物件寫入一些人員資訊,比如姓名和年齡。
 public static void writeFile() throws IOException{
  /*
   * 如果檔案不存在,則建立,如果檔案存在,不建立
   *
   */
  RandomAccessFile raf = new RandomAccessFile("ranacc.txt","rw");
  
  raf.write("張三".getBytes());
  raf.writeInt(97);
  raf.write("小強".getBytes());
  raf.writeInt(99);
//  
  raf.close();
 }

}

相關文章