RandomAccessFile類
該類主要是對文件內容進行操作,可以隨機的讀取一個文件中指定位置的數據;
但是如果想實現這樣的功能,則每個數據的長度應該保持一致;
構造方法:
接受File類中的對象,但是在設置時需要設置模式,r:只讀;w:只寫;rw:讀寫(常用)
public
RandomAccessFile(File file, String mode)throws FileNotFoundException
不再使用File類對象表示文件,而是直接輸入了一個固定的文件路徑
public
RandomAccessFile(String name,String mode)throws FileNotFoundException
常用功能:
關閉操作
public void
close()throws IOException
將一個字符串寫入到文件中,按字節的方式處理
public final void
writeBytes(String s)throws IOException
將一個int型數據寫入文件,長度為4位
public final void
writeInt(int v)throws IOException
指針跳過多少個字節
public int
skipBytes(int n)throws IOException
將內容讀取到byte數組中
public int
read(byte[] b)throws IOException
讀取一個字節
public final byte
readByte()throws IOException
從文件中讀取整型數據
public final int
readInt()throws IOException
設置讀指針的位置
public void
seek(long pos)throws IOException
package cn.itcast02;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteOrder;
public class DemoRandowAccessFile01 {
public static void main(String[] args) throws IOException {
File file = new File("G:" + File.separator +"JavaTest"+File.separator + "test01.txt" );
/*
RandomAccessFile rdf = new RandomAccessFile(file, "rw");
//寫入文件內容
String name = " liuyan ";
int age = 40;
rdf.writeBytes(name);
rdf.writeInt(age);
String name2 = " xiaoming";
int age2 = 30;
rdf.writeBytes(name2);
rdf.writeInt(age2);
String name3 = " doudou ";
int age3 = 24;
rdf.writeBytes(name3);
rdf.writeInt(age3);
rdf.close();
*/
//讀取文件內容
RandomAccessFile rdf = new RandomAccessFile(file, "r" );
//創建空間存放姓名
byte[] bytes = new byte[8];
rdf.skipBytes(12);
for (int i = 0; i < bytes.length; i++) {
bytes[i] = rdf.readByte();
}
//將byte轉化為String
String name = new String(bytes);
int age = rdf.readInt();
System. out.println("第二個人信息" +"姓名:" +name+" " +"年齡:" +age);
//指針返回到文件開頭
rdf.seek(0);
rdf.close();
}
}
輸出:
第二個人信息姓名:xiaoming 年齡:30