首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

Java RandomAccessFile 隨機讀寫文件:定位、跳過、讀寫字節完整示例

     編輯:關於C++

RandomAccessFile 核心能力

支持**隨機訪問**文件任意位置:
- seek(long pos):移動文件指針。
- skipBytes(int n):相對當前位置前移。
- readByte()、writeByte() 等基本類型讀寫。
模式 "rw" 可讀可寫,"r" 唯讀。

完整演示代碼


import java.io.*;

public class RAFDemo {
    public static void main(String[] args) throws IOException {
        File f = new File("d:/text.txt");
        // 寫入
        try (RandomAccessFile raf = new RandomAccessFile(f, "rw")) {
            raf.writeBytes("zhangsan");
        }
        // 讀取演示
        readDemo(f);
    }

    static void readDemo(File f) throws IOException {
        try (RandomAccessFile raf = new RandomAccessFile(f, "r")) {
            byte b1 = raf.readByte();          // 讀第 1 字節 'z' (122)
            System.out.println("b1: " + b1);
            raf.skipBytes(5);                  // 跳過 5 字節,指針到 'a'
            byte b2 = raf.readByte();          // 讀 'a' (97)
            System.out.println("b2: " + b2);
            raf.seek(3);                       // 絕對定位到索引 3 'n'
            byte b3 = raf.readByte();          // 讀 'n' (110)
            System.out.println("b3: " + b3);
            System.out.println("Combined: " + new String(new byte[]{b1,b2,b3})); // "zan"
        }
    }
}

輸出解析


b1: 122
b2: 97
b3: 110
Combined: zan

文件內容 "zhangsan",索引 0='z', 3='n', 5='a'。skipBytes(5) 從索引 1 移到 6?實際演示中 skipBytes(5) 後讀到 'a'(索引 5),說明 skipBytes 從**當前位置**向前跳過指定字節數。

進階用法

  • readInt()/writeInt() 等處理基本類型(大端序)。
  • getFilePointer() 獲取當前指針位置。
  • length() 獲取文件長度。
  • setLength(len) 截斷/擴展文件。

適用場景

  • 大文件隨機讀取(如視頻跳轉、數據庫索引)。
  • 文件修改中間數據(不需整體讀入內存)。
  • 實現簡易鍵值存儲(固定長度記錄)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved