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