EchoDemo's Blogs

Java中的RandomAccessFile

1、RandomAccessFile(随机访问文件)支持对随机访问文件的读取和写入。随机访问文件的行为类似存储在文件系统中的一个大型byte数组。存在指向该隐含数组的光标或索引,称为文件指针。

2、输入操作从文件指针开始读取字节,随着对字节的读取而前移此文件指针。如果随机访问文件以读取/写入模式创建,则输出操作也可用;输出操作从文件指针开始写入字节,随着对字节的写入而前移此文件指针。

3、写入该隐含数组末尾之后的输出操作导致该数组扩展。该文件指针可以通过getFilePointer方法读取,通过seek方法设置该文件指针的位置。

4、RandomAccessFile举例

package com.iotek.otherio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;

public class RandomAccessFileDemo {

    public static void main(String[] args) throws IOException {
        Person[] persons = {new Person("chenhao",90),
                new Person("justin",30),new Person("bush",80),
                new Person("lisi",20)};
        RandomAccessFile randomAccessFile = new RandomAccessFile("f:\\test\\3.txt", "rw");
        /*for(int i=0;i<persons.length;i++){//写入数据到RandomAccessFile这个对象中
            randomAccessFile.writeChars(persons[i].getName());
            randomAccessFile.writeInt(persons[i].getAge());
        }*/

        //读取指定位置上的Person对象
        Scanner scanner = new Scanner(System.in);
        System.out.println("读取第几个Person对象数据");
        int num = scanner.nextInt();
        //使用seek方法来操作存取位置
        randomAccessFile.seek((num-1)*Person.size());
        Person person = new Person();
        person.setName(readName(randomAccessFile));
        person.setAge(randomAccessFile.readInt());
        System.out.println("姓名:"+person.getName());
        System.out.println("年龄:"+person.getAge());
        randomAccessFile.close();
    }

    private static String readName(RandomAccessFile randomAccessFile) throws IOException{
        char[] name = new char[15];
        for(int i=0;i<name.length;i++){
            name[i] = randomAccessFile.readChar(); 
        }
        return new String(name).replace('\u0000', ' ');
    }
}

class Person{

    private String name;
    private int age;
    public Person(){

    }

    public Person(String name, int age) {
        StringBuilder builder = null;
        if(name!=null){
            builder = new StringBuilder(name);
        }else{
            builder = new StringBuilder(15);
        }
        builder.setLength(15);//固定长度为15个,占了30个字节大小,不足时会自动补'\u0000'
        this.name = builder.toString();
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        StringBuilder builder = null;
        if(name!=null){
            builder = new StringBuilder(name);
        }else{
            builder = new StringBuilder(15);
        }
        builder.setLength(15);//固定长度为15个,占了30个字节大小,不足时会自动补'\u0000'
        this.name = builder.toString();
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    //每个对象所占的字节数
    public static int size(){
        return 34;
    }
}
🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------