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

Java 讀取 FoxPro 格式 DBF 檔案原始碼解析與實作

     編輯:Java 相關知識

前言

整理完成 DBF 檔案讀寫的 Java 原始碼,供開發者參考使用。本文重點解析關鍵邏輯:標頭解析、欄位定義讀取與記錄資料提取。

核心程式碼片段

1. 初始化與標頭讀取

private void init(InputStream inputstream) throws JDBFException {
    try {
        stream = new DataInputStream(inputstream);
        int fieldCount = readHeader();           // 讀取標頭,取得欄位數
        fields = new JDBField[fieldCount];
        int recordLength = 1;                    // 記錄長度起始值(含刪除標記位元組)

        for (int k = 0; k < fieldCount; k++) {
            fields[k] = readFieldHeader();       // 讀取每個欄位定義
            recordLength += fields[k].getLength(); // 累加欄位長度
        }

        if (stream.read() < 1) throw new JDBFException("Unexpected end of file reached.");

        nextRecord = new byte[recordLength];
        try {
            stream.read(new byte[263]);          // 略過標頭結尾保留區塊
            stream.readFully(nextRecord);        // 讀取第一筆記錄
        } catch (EOFException eofexception) {
            nextRecord = null;
            stream.close();
        }
    } catch (IOException ioexception) {
        throw new JDBFException(ioexception);
    }
}

2. 標頭解析邏輯

private int readHeader() throws IOException, JDBFException {
    byte[] headerBytes = new byte[16];
    try {
        stream.readFully(headerBytes);
    } catch (EOFException e) {
        throw new JDBFException("Unexpected end of file reached.");
    }

    // 位元組 8、9 記錄標頭長度(含終止標記)
    int headerLen = headerBytes[8] & 0xFF;
    headerLen += 256 * (headerBytes[9] & 0xFF);
    headerLen -= 264;                            // 扣除固定標頭大小
    headerLen = --headerLen / 32;                // 每欄位 32 位元組,換算欄位數

    // 讀取標頭結尾標記
    try {
        stream.readFully(headerBytes);
    } catch (EOFException e) {
        throw new JDBFException("Unexpected end of file reached.");
    }
    return headerLen;
}

DBF 檔案格式參考

詳細格式定義請參考:DBF File Format Specification

實作注意事項

  • 程式碼假設檔案結構符合標準 DBF 規範(如 FoxPro / dBase III+)。
  • 欄位長度累加需包含記錄開頭的刪除標記位元組(0x20 或 0x2A)。
  • 實際專案建議加入編碼轉換處理(DBF 常用 CP850、Big5 等編碼)。
  • 大檔案讀取時建議使用 RandomAccessFile 或 NIO 提升效能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved