天天看點

【Java】IO ---- RandomAccessFile

内容目錄

  • 概述
  • 4種模式
  • 如何随機通路一部分資料
  • 如何在指定位置追加一段資料

概述

RandomAccessFile ----- 自由通路檔案任意位置

1、概念:RandomAccessFile是直接繼承Object的獨立的類,是用來通路那些儲存資料記錄的檔案的,用seek( )方法來進行讀寫了。

public RandomAccessFile(String name, String mode)

2、方法

  • file poniter — 檔案指針 用來标記目前讀取或寫入的位置
  • getFileponiter()— 傳回目前檔案指針的位置
  • seek() — 設定目前檔案指針的位置

4種模式

  • r:隻讀模式
  • rw:支援讀取和寫入
  • rws:支援讀取和寫入,同時當我們修改檔案内容和檔案的中繼資料都會直接同步到儲存設備上
  • rwd:支援讀取和寫入,同時當我們修改檔案内容會直接同步到儲存設備上

PS:檔案的中繼資料是什麼?

檔案的大小,通路權限,包括本身一些屬性資訊

随機通路檔案中的某一部分資料

RandomAccessFile file = null;
        try {
            file = new RandomAccessFile("a.txt", "r");

            file.seek(50);
            System.out.println(file.getFilePointer());

            byte[] bytes = new byte[256];
            int hasRead = file.read(bytes);
            System.out.println(new String(bytes, 0, hasRead));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
           

在指定位置去追加一段資料

PS:RandomAccessFile不能在任意位置去追加資料

public static void main(String[] args) {
        RandomAccessFile raf = null;
        File file = null;
        FileOutputStream fos = null;
        FileInputStream fis = null;

        try {
            //建立臨時檔案
            File.createTempFile("test.txt", null);

            //建立輸入、輸出流
            fis = new FileInputStream("test.txt");
            fos = new FileOutputStream("test.txt");

            //建立RandomAccessFile對象
            raf = new RandomAccessFile("a.txt", "rw");
            //移動檔案指針
            raf.seek(50);

            //讀取該位置之後的資料,并把它寫入到臨時檔案裡
            byte[] bytes = new byte[256];
            int hasRead = 0;
            while((hasRead = raf.read(bytes)) != -1){
                fos.write(bytes, 0,  hasRead);
            }

            //移動檔案指針
            raf.seek(50);
            //往檔案中指定位置追加内容
            raf.write("tulun software company".getBytes());

            //追加檔案
            while((hasRead = fis.read(bytes)) != -1){
                raf.write(bytes, 0 , hasRead);
            }
            
             } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                raf.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }