此類的執行個體支援對随機通路檔案的讀取和寫入。随機通路檔案的行為類似存儲在檔案系統中的一個大型 byte 數組。存在指向該隐含數組的光标或索引,稱為檔案指針;輸入操作從檔案指針開始讀取位元組,并随着對位元組的讀取而前移此檔案指針。如果随機通路檔案以讀取/寫入模式建立,則輸出操作也可用;輸出操作從檔案指針開始寫入位元組,并随着對位元組的寫入而前移此檔案指針。寫入隐含數組的目前末尾之後的輸出操作導緻該數組擴充。該檔案指針可以通過 getFilePointer seek
方法讀取,并通過
方法設定。
通常,如果此類中的所有讀取例程在讀取所需數量的位元組之前已到達檔案末尾,則抛出
EOFException
(是一種 IOException
)。如果由于某些原因無法讀取任何位元組,而不是在讀取所需數量的位元組之前已到達檔案末尾,則抛出 IOException
,而不是 EOFException
。需要特别指出的是,如果流已被關閉,則可能抛出 IOException
。
構造方法:
import java.io.File;
import java.io.RandomAccessFile;
public class Main {
public static void main(String[] args) throws Exception {
// 1
RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
// 2
File file = new File("hello.txt");
RandomAccessFile randomAccessFile1 = new RandomAccessFile(file,"rw") ;
}
}
方法摘要:
close() 關閉RandomAccessFile執行個體打開的檔案。
1 import java.io.RandomAccessFile;
2
3 public class Main {
4 public static void main(String[] args) throws Exception {
5 RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
6 randomAccessFile.close();
7 }
8 }
seek() 檔案指針移動。
1 import java.io.RandomAccessFile;
2
3 public class Main {
4 public static void main(String[] args) throws Exception {
5 RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
6 // seek 參數為 long
7 long w = 100 ;
8 randomAccessFile.seek(w);
9 randomAccessFile.close();
10 }
11 }
length() 檔案長度
1 import java.io.RandomAccessFile;
2
3 public class Main {
4 public static void main(String[] args) throws Exception {
5 RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
6 long len = randomAccessFile.length();
7 randomAccessFile.close();
8 }
9 }
讀取:
read()
read(byte[] b)
read(byte[] b,int off,int len)
readLine()
readBoolean()
readDouble()
readFloat()
readByte()
readChar()
寫入:
write(byte []b)
write(byte []b,int off,int len)
write(int b)
writeBoolean(boolean v)
writeByte(int v)
writeBytes(String s)
writeChar(int v)
writeChars(String s)
writeDouble(double v)
writeFloat(float v)
writeInt(int v)
writeLong(long v)
writeShort(int v)
writeUTF(String str)
注 : RandomAccessFile可利用多線程完成對一個大檔案的讀寫,利用seek對檔案進行切分,從大檔案的不同位置開線程進行讀寫。