(IO操作流)RandomAccessFile

RandomAccessFile(ランダム読み取りクラス)

ファイルコンテンツの処理操作は、主にInputStream(リーダー)とOutputStream(ライター)を介して実現されますが、これらのクラスによって実現されるコンテンツの読み取りは、データ部分の一部しか読み取ることができません。

非常に大きなファイルを作成します。このファイルのサイズは20Gです。現時点で従来のIO操作に従ってファイルを読み取って分析すると、完了することができないため、この場合、JavaにRandomAccessFileクラスがあります。 .ioパッケージ。このクラスは、ファイルのジャンプタイプの読み取りを実現でき、コンテンツの中央部分のみを読み取ることができ(前提条件:完全なストレージ形式が必要です)、データストレージビットの数を決定する必要があります。

 RandomAccessFileクラスでは、次のメソッドが定義されています。

  • コンストラクター方法:publicRandomAccessFile(ファイルファイル、文字列モード)はFileNotFoundExceptionをスローします

ファイル処理モード:r、rw

例:ファイルの保存を実現する

package IO深入操作;

import java.io.File;
import java.io.RandomAccessFile;

public class RandomAccessFile类 {
    public static void main(String[] args) throws Exception{
        File file = new File("D:\\Test\\test"); //定义操作文件
        RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");    //读写模式
        String[] names = new String[]{"zhangsan","lisi    ","wangwu  "};
        int[] age = new int[]{20,30,16};
        for(int x = 0;x < names.length;x++){
            randomAccessFile.write(names[x].getBytes());    //写入字符串
            randomAccessFile.writeInt(age[x]);    //写入数字
        }
    }
}

RandomAccessFileの最大の特徴は、データが読み取られないことです。すべてのデータは固定長に従って保存されるため、読み取るときにバイトをスキップして読み取ることができます。

  • ジャンプダウン:public int skipBytes(int n)throws IOException
  • 向回跳:public void seek(long pos)throws IOException

例:データの読み取り

package IO深入操作;

import java.io.File;
import java.io.RandomAccessFile;

public class RandomAccessFile类 {
    public static void main(String[] args) throws Exception{
        File file = new File("D:\\Test\\test"); //定义操作文件
        RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");    //读x写模式
        {//读取王五的数据,跳过24位
            randomAccessFile.skipBytes(24);
            byte[] data  =  new byte[8];
            int len = randomAccessFile.read(data);
            System.out.println("姓名:"+new String(data,0,len)+"年龄:"+ randomAccessFile.readInt());
        }
        {  //读取李四的数据,回跳12位
            randomAccessFile.seek(12);
            byte[] data  =  new byte[8];
            int len = randomAccessFile.read(data);
            System.out.println("姓名:"+new String(data,0,len)+"年龄:"+ randomAccessFile.readInt());
        }
        {  //读取张三的数据,回跳到头
            randomAccessFile.seek(0);   //回到顶点
            byte[] data  =  new byte[8];
            int len = randomAccessFile.read(data);
            System.out.println("姓名:"+new String(data,0,len)+"年龄:"+ randomAccessFile.readInt());
            randomAccessFile.close();
        }
    }
}

 

全体的な使用法では、読み取る位置は自分で決定し、次に、自分を知っている構造に従ってデータを読み取ります。

 

おすすめ

転載: blog.csdn.net/weixin_46245201/article/details/112969923