文件的随机读写

RandomAccessFile类

  • 该类不是IO体系中的子类,因为它直接继承Object.
  • 但它是IO体系中的成员,具有读和写的双重功能(因为内部封装了字节输入/输出流)
  • 内部封装了一个数组,并且通过指针来操作,可以使用getFilePointer()来获取指针位置以及用seek()来调整指针位置
  • 该对象只能操作文件,并且可以通过参数来设置操作文件的模式
构造函数

RandomAccessFile(File file, String mode)
创建从中读取和向其中写入(可选)的随机访问文件流,该文件由 File 参数指定。
RandomAccessFile(String name, String mode)
创建从中读取和向其中写入(可选)的随机访问文件流,该文件具有指定名称。

使用示例①

public class 文件的随机读写 {

    public static void main(String[] args) throws IOException {
        xie();
        du();
    }
//写入信息
    public static void xie() throws IOException {
        File f = new File("F:\\IO学习专用文件夹\\学生信息.txt");
        RandomAccessFile romf = new RandomAccessFile(f, "rw");
//存入信息,共占用34个字节,其中前30个用来存姓名,后4个用来存年龄
        for(int index=0 ; index<=20 ; index++){
            String name="张三"+index;
            int len=name.length();
//使用seek()改变指针位置
            romf.seek(34*index);
            romf.write(name.getBytes());
            romf.seek(34*index+30);
            romf.writeInt(20+index);
        }
        romf.close();
    }
//读出信息
    public static void du() throws IOException{
        File f = new File("F:\\IO学习专用文件夹\\学生信息.txt");
        RandomAccessFile romf = new RandomAccessFile(f, "rw");
        byte [] b=new byte[30];
        int len;
        while((len=romf.read(b))!=-1){
            int age=romf.readInt();
            sop("name->"+new String(b)+"    age->"+age);
        }
        romf.close();
    }
}
  • 就像上例,RandomAccessFile可以将一些信息安照一定的格式存入文件并且再读出来

使用示例②(修改或者在指定位置写入/获取数据)

public class Test {
    public static void main(String [] args) throws IOException{
        xie();
//        du();
    }
    public static void xie() throws IOException {
        File f = new File("F:\\IO学习专用文件夹\\学生信息2.txt");
        if(!f.exists())
            f.createNewFile();
        RandomAccessFile romf = new RandomAccessFile(f, "rw");
        romf.write("张三".getBytes());
        romf.writeInt(20);
        //写入张三后空10个字节再存李四的信息
        romf.seek(10*3);
        romf.write("李四".getBytes());
        romf.writeInt(22);
        //将指针回到0位置,王五的信息将张三的信息覆盖
        romf.seek(10*0);
        romf.write("王五".getBytes());
        romf.writeInt(24);
        romf.close();
    }
    public static void du() throws IOException{
        File f = new File("F:\\IO学习专用文件夹\\学生信息2.txt");
        RandomAccessFile romf = new RandomAccessFile(f, "rw");
        byte [] b=new byte[6];
        //跳过10个字节再读取
        romf.skipBytes(10);
        romf.read(b);
        int age=romf.readInt();
        sop("name->"+new String(b)+"    age->"+age);
        romf.close();
    }
}
注意
  • 在utf-8下一个汉字占3个字节,在GBK中才占2个字节
  • 当模式为r即只读模式时,如果文件不存在会抛出FileNotFoundException异常;如果模式为rw即读写模式,文件不存在就会创建,存在就会续写,但是此时指针会归零!!!
  • getBytes()方法是通过读取几个字节并丢弃掉来实现的,因此它不能使指针前移,也不能在指针后面没有数据的时候使指针后移
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容