隨機訪(fǎng)問(wèn)類(lèi)(RandomAccessFile) - []
輸入流FileInputStream和輸出流 FileOutputStream,實(shí)現的是對磁盤(pán)文件的順序讀寫(xiě),而且讀寫(xiě)要分別創(chuàng )建不同對象。相比之下RandomAccessFile類(lèi)則可對文件實(shí)現隨機讀寫(xiě)操作。
RandomAccessFile對象的文件位置指針遵循下面的規律:
·新建RandomAccessFile對象的文件位置指針位于文件的開(kāi)頭處;
·每次讀寫(xiě)操作之后,文件位置的指針都相應后移到讀寫(xiě)的字節數;
·可以通過(guò)getFilePointer方法來(lái)獲得文件位置指針的位置,通過(guò)seek方法來(lái)設置文件指針的位置。
如果某個(gè)文件有30個(gè)字節,讀取數據過(guò)程中,從20-30讀取,用skip( )//跳過(guò)方法,但在讀取的過(guò)程中,前面的字節都被刪除掉了,如果用戶(hù)有這樣的需求,先讀取10-20字節,之后再讀1-10之間的數,再20-30之間,
java.io
隨機訪(fǎng)問(wèn)文件類(lèi) RandomAccessFile java.io.RandomAccessFile
所有已實(shí)現的接口:
Closeable, DataInput, DataOutput
|0 ||10 ||20 ||30 |
(指示器)
RandomAccessFile常用方法:
skipBytes(long i):從前往后撥弄指示器的位置,就是跳過(guò)多少個(gè)字節讀取數據。
Void seek(long p): 對指示器作決定性的定位,用于從后往前撥弄指示器的位置。對于seek方法,擁有skipBytes( )的功能,但seek( )在使用過(guò)程非常影響系統的開(kāi)銷(xiāo)。只有萬(wàn)不得已的情況下使用。
例:seek(0) 指示器移到首部
RandomAccessFile類(lèi),即可以充當輸入也可充當輸出流??梢钥醋鞴濣c(diǎn)流。
構造方法:
RandomAccessFile (”路徑+文件名”, String“rw”/”r”)兩個(gè)參數,
//創(chuàng )建模式:“rw”代表寫(xiě)流,“r”代表讀流,
RandomAccessFile常用方法
Void close( )
Long length( )
Void seek( )
##Long getFilePointer( )獲得當前指針位置,默認為0 ,
Int read( )從文件當前位置讀取一個(gè)字節
int read (byte[]b)
int read (byte[]b,int off,int len)
Final boolean readBoolean( )從文件當前位置讀取boolean類(lèi)型的一個(gè)字節 boolean在內存占1/8
Final char readChar( )從文件中讀取2個(gè)字節。
Final int readInt( )從文件中讀取4個(gè)字節。
##Final String readLine( )從文件中讀取一行后轉為String。
Void write(byte[]b)將字節數組B中的數據寫(xiě)到文件中。
Void write(byte[]b,int off,int len)將 len 個(gè)字節從指定字節數組寫(xiě)入到此文件,并從偏移量 off 處開(kāi)始。
Void write(int b)將指定的數據寫(xiě)到文件中。
Final void writeBoolean(boolean v)將boolean類(lèi)型的值按單字節的形式寫(xiě)到文件中0或1
Final void writeChar(int v)將char值按2個(gè)字節寫(xiě)入到文件中
Final void writeChars(String s)將字符串按字符方式寫(xiě)入到文件中
Final void writeInt(int v)按四個(gè)字節將 int 寫(xiě)入該文件,先寫(xiě)高字節
- 例:getFilePointer( )
- import java.io.*;
-
- class df
- {
- public static void main(String args[])throws Exception
- {
- RandomAccessFile s=new RandomAccessFile("d:/tt.txt","rw");
- System.out.println ( s.getFilePointer( ));
- }
- }
-
例:getFilePointer( )import java.io.*;class df{public static void main(String args[])throws Exception{RandomAccessFile s=new RandomAccessFile("d:/tt.txt","rw");System.out.println ( s.getFilePointer( ));//0}} 例:
- import java.io.*;
- class RandomAccessFileDemo
- {
-
-
- public static void main(String args[])throws IOException
-
- {
-
- RandomAccessFile f=new RandomAccessFile("myfile","rw");
- System.out.println ("File.lelngth:"+(f.length( ))+"B");
- System.out.println ("File PointPosition:"+f.getFilePointer( ));
- f.seek(f.length( ));
- f.writeBoolean(true);
- f.writeBoolean(false);
- f.writeChar(’a’);
- f.writeChars("hello!");
- System.out.println ("File Length;"+(f.length( ))+"B");
-
- f.seek(0);
- System.out.println (f.readBoolean( ));
- System.out.println (f.readBoolean( ));
-
- System.out.println (f.readLine( ));
- f.close( );
- }}