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 < name.length; 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();
}
}
整个使用流程之中,由用户自行定义读取的位置而后按照指定的结构进行数据的读取。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)