更新時間:2020-12-04 17:54:54 來源:動力節(jié)點 瀏覽1222次
RandomAccessFile類創(chuàng)建的流稱作java隨機流,RandomAccessFile類既不是InputStream類的子類,也不是OutputStream類的子類。隨機流不屬于IO流,支持對文件的讀取和寫入隨機訪問。當準備對一個文件進行讀寫操作時,創(chuàng)建一個指向該文件的隨機流即可,這樣既可以從這個流中讀取文件的數據,也可以通過這個流寫入數據到文件。
隨機流是一種具備雙向傳輸能力的特殊流。IO流中的各個流都只能實現單向的輸入或輸出操作,如果想對一個文件進行讀寫操作就要建立兩個流。隨機流 Random Access File 類創(chuàng)建的流既可以作為輸入流,也可以作為輸出流,因此建立一個隨機流就可以完成讀寫操作。
RandomAccessFile類的定義:
public class RandomAccessFile extends Object
implements DataOutput, DataInput, Closeable
構造方法:
public RandomAccessFile(File file,String mode) throws FileNotFoundException
Random Access File 類與其他流不同,它既不是 Input Stream 類的子類,也不是 Output Stream 的子類,而是 java.lang.Object 根類的子類。RandomAccessFile最大的特點實在數據的讀取處理上,因為所有的數據時按照固定的長度進行的保存,所以讀取的時候就可以進行跳字節(jié)讀取。
主要方法:
public int skipBytes(int n) throws IOException//向下跳
public void seek(long pos) throws IOException//向回跳
隨機流的輸入和輸出實例:
/*
* 實現文件的保存
*/
package IODemo;
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
File file = new File("D:"+File.separator+"mldn.txt");
RandomAccessFile raf = new RandomAccessFile(file,"rw");
String[] names = new String[] {"zhangsan","wangwu ","lisi "};//名字占8位
int age[] = new int[] {30,20,16};//年齡占4位
for(int x = 0 ; x < names.length ; x++) {
raf.write(names[x].getBytes());
raf.writeInt(age[x]);
}
raf.close();
}
}
/*
* 讀取數據
*/
package IODemo;
import java.io.*;
public class RandomAccessFileDemo2 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
File file = new File("D:"+File.separator+"mldn.txt");
RandomAccessFile raf = new RandomAccessFile(file,"rw");
{//讀取lisi數據,跳過24位
raf.skipBytes(24);
byte[] data = new byte[8];
int len = raf.read(data);
System.out.println("姓名:"+new String(data,0,len).trim()+"年齡:"+raf.readInt());
}
{//讀取wangwu數據,回跳12位
raf.seek(12);
byte[] data = new byte[8];
int len = raf.read(data);
System.out.println("姓名:"+new String(data,0,len).trim()+"年齡:"+raf.readInt());
}
{//讀取zhangsan數據,回跳到頂點
raf.seek(0);
byte[] data = new byte[8];
int len = raf.read(data);
System.out.println("姓名:"+new String(data,0,len).trim()+"年齡:"+raf.readInt());
}
}
}
Random Access File 類的實例對象支持對文件的隨機訪問。這種隨機訪問文件的過程可以看作是訪問文件系統(tǒng)中的一個大型 Byte 數組,指向數組位置的隱含指針稱為文件指針。輸入操作從文件指針位置開始讀取字節(jié),并隨著對字節(jié)的讀取移動此文件指針。輸出操作從文件指針位置開始寫入字節(jié),并隨著對字節(jié)的寫入而移動此文件指針。因此,隨機流可以用于多線程文件下載或上傳,為快速完成訪問提供了便利。想要掌握隨機流用法的小伙伴,可以在本站的Java基礎教程中繼續(xù)深入學習。