解決java-dbf中文標題亂碼的問題


項目中需要對DBF的文件進行導入處理,上網搜了發現有java-dbf這個東西。實際應用中踩了不少坑,主要就是中文亂碼的問題。

        InputStream in = new FileInputStream("D:\\test.dbf");
        DBFReader reader = new DBFReader(in);
        reader.setCharactersetName("GBK");
        for(int i = 0; i < reader.getFieldCount(); i++){
            DBFField field = reader.getField(i);
            System.out.print(field.getName() + ",");
        }
        System.out.print("\r\n");
        Object[] values;
        while ( (values = reader.nextRecord()) != null ){
            for(Object value : values){
                System.out.print(value.toString() + ",");
            }
            System.out.print("\r\n");
        }

網上寫法千篇一律,大概就是這樣。問題來了DBF中具體數據的中文亂碼通過reader.setCharactersetName("GBK")解決了。

 

但是發現列名的亂碼還是沒有解決。

 

后來查了一下源碼,發現了問題所在

    public DBFReader(InputStream in, Charset charset, boolean showDeletedRows) {
        try {
            this.showDeletedRows = showDeletedRows;
            this.inputStream = in;
            this.dataInputStream = new DataInputStream(this.inputStream);
            this.header = new DBFHeader();
            this.header.read(this.dataInputStream, charset, showDeletedRows);
            setCharset(this.header.getUsedCharset());
            /* it might be required to leap to the start of records at times */
            int fieldSize = this.header.getFieldDescriptorSize();
            int tableSize = this.header.getTableHeaderSize();
            int t_dataStartIndex = this.header.headerLength - (tableSize + (fieldSize * this.header.fieldArray.length)) - 1;            
            skip(t_dataStartIndex);
            
            this.mapFieldNames = createMapFieldNames(this.header.userFieldArray);
        } catch (IOException e) {
            DBFUtils.close(dataInputStream);
            DBFUtils.close(in);
            throw new DBFException(e.getMessage(), e);
        }
    }

其中header就是我們讀取的列名,列數所依靠的成員變量,但是這個變量在對象創建的時候就賦值好了。

這就導致了后來即使調用了setCharactersetName也解決不了列名亂碼問題。

所以我們要從根本上解決問題,創建對象的時候直接傳入charset對象。

 

修改后代碼如下

    public static void main(String[] args) throws FileNotFoundException {
        InputStream in = new FileInputStream("D:\\test.dbf");
        Charset charset = Charset.forName("GBK");
        DBFReader reader = new DBFReader(in,charset);
        for(int i = 0; i < reader.getFieldCount(); i++){
            DBFField field = reader.getField(i);
            System.out.print(field.getName() + ",");
        }
        System.out.print("\r\n");
        Object[] values;
        while ( (values = reader.nextRecord()) != null ){
            for(Object value : values){
                System.out.print(value.toString() + ",");
            }
            System.out.print("\r\n");
        }
    }

 

輸出時候列名就正常了



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM