更新時(shí)間:2020-12-04 17:54:54 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1168次
RandomAccessFile類創(chuàng)建的流稱作java隨機(jī)流,RandomAccessFile類既不是InputStream類的子類,也不是OutputStream類的子類。隨機(jī)流不屬于IO流,支持對文件的讀取和寫入隨機(jī)訪問。當(dāng)準(zhǔn)備對一個(gè)文件進(jìn)行讀寫操作時(shí),創(chuàng)建一個(gè)指向該文件的隨機(jī)流即可,這樣既可以從這個(gè)流中讀取文件的數(shù)據(jù),也可以通過這個(gè)流寫入數(shù)據(jù)到文件。
隨機(jī)流是一種具備雙向傳輸能力的特殊流。IO流中的各個(gè)流都只能實(shí)現(xiàn)單向的輸入或輸出操作,如果想對一個(gè)文件進(jìn)行讀寫操作就要建立兩個(gè)流。隨機(jī)流 Random Access File 類創(chuàng)建的流既可以作為輸入流,也可以作為輸出流,因此建立一個(gè)隨機(jī)流就可以完成讀寫操作。
RandomAccessFile類的定義:
public class RandomAccessFile extends Object
implements DataOutput, DataInput, Closeable
構(gòu)造方法:
public RandomAccessFile(File file,String mode) throws FileNotFoundException
Random Access File 類與其他流不同,它既不是 Input Stream 類的子類,也不是 Output Stream 的子類,而是 java.lang.Object 根類的子類。RandomAccessFile最大的特點(diǎn)實(shí)在數(shù)據(jù)的讀取處理上,因?yàn)樗械臄?shù)據(jù)時(shí)按照固定的長度進(jìn)行的保存,所以讀取的時(shí)候就可以進(jìn)行跳字節(jié)讀取。
主要方法:
public int skipBytes(int n) throws IOException//向下跳
public void seek(long pos) throws IOException//向回跳
隨機(jī)流的輸入和輸出實(shí)例:
/*
* 實(shí)現(xiàn)文件的保存
*/
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();
}
}
/*
* 讀取數(shù)據(jù)
*/
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數(shù)據(jù),跳過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數(shù)據(jù),回跳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數(shù)據(jù),回跳到頂點(diǎn)
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 類的實(shí)例對象支持對文件的隨機(jī)訪問。這種隨機(jī)訪問文件的過程可以看作是訪問文件系統(tǒng)中的一個(gè)大型 Byte 數(shù)組,指向數(shù)組位置的隱含指針稱為文件指針。輸入操作從文件指針位置開始讀取字節(jié),并隨著對字節(jié)的讀取移動(dòng)此文件指針。輸出操作從文件指針位置開始寫入字節(jié),并隨著對字節(jié)的寫入而移動(dòng)此文件指針。因此,隨機(jī)流可以用于多線程文件下載或上傳,為快速完成訪問提供了便利。想要掌握隨機(jī)流用法的小伙伴,可以在本站的Java基礎(chǔ)教程中繼續(xù)深入學(xué)習(xí)。
初級 202925
初級 203221
初級 202629
初級 203743