作者:爱的伤痕累2602882347_111 | 来源:互联网 | 2023-10-10 11:08
RandomAccessFile:RandomAccessFile的数据最重要的一点就是:数据的结构一致。RandomAccessFile类里面定义有如下的操作方法:构造方法:pu
RandomAccessFile:RandomAccessFile的数据最重要的一点就是:数据的结构一致。
RandomAccessFile类里面定义有如下的操作方法:
构造方法:public RandomAccessFile(File file,String mode) throwsFileNotFoundException;
文件处理模式:r、rW;
进行写的操作:
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
public class MAIN {
public static void main(String[] args) throws Exception {
File file = new File("D:" + File.separator + "Demo_2_15" + File.separator + "Copy.txt" );
RandomAccessFile ra = new RandomAccessFile(file,"rw"); // 读写模式
String[] name = new String[]{"zhangsan","wangwu ", "lisi "};
int [] ages = new int[]{20,15,16};
for (int i = 0; i ) {
ra.write(name[i].getBytes(StandardCharsets.UTF_8)); // 写入字符串
ra.writeInt(ages[i]); // 写入
}
ra.close();
}
}
写入完成。
RandomAccessFile最大的特点是在于数据的读取处理上,因为所有的数据是按照固定的长度进行保存,所以读取的时候就可以进行跳字节读取。
向下跳: public int skipBytes(int n) throws IOException;
向回跳: public void seek(long pos) throws IOException。
读取操作:
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
public class MAIN {
public static void main(String[] args) throws Exception {
File file = new File("D:" + File.separator + "Demo_2_15" + File.separator + "Copy.txt" );
RandomAccessFile ra = new RandomAccessFile(file,"rw"); // 读写模式
{
ra.skipBytes(24); // 读取李四的数据,跳过16位
byte[] data = new byte[8];
int len = ra.read(data);
System.out.println("name = " + new String(data,0,len).trim() + "\tages = " + ra.readInt());
}
{
ra.skipBytes(24); // 读取王五的数据,回跳到12位
ra.seek(12); // 从12位开始
byte[] data = new byte[8];
int len = ra.read(data);
System.out.println("name = " + new String(data,0,len).trim() + "\tages = " + ra.readInt());
}
{
ra.skipBytes(24); // 读取zhangsan的数据,回跳到首位
ra.seek(0); // 从0开始
byte[] data = new byte[8];
int len = ra.read(data);
System.out.println("name = " + new String(data,0,len).trim() + "\tages = " + ra.readInt());
}
ra.close();
}
}
整个使用流程之中,由用户自行定义读取的位置而后按照指定的结构进行数据的读取。