簡體   English   中英

霍夫曼編碼文件保存

[英]Huffman coding file saving

我編寫了一個使用霍夫曼編碼的程序,以獲取一個.txt文件並將其壓縮。 該程序將壓縮的代碼保存為.hzip文件。 在我嘗試壓縮並保存包含換行符的文件之前,代碼可以正常工作。 這是我保存文件的代碼:

private void codeToFile() {

    String code = "";
    char letter;

    String fileName = this.encodeFileName.replace(".txt", ".hzip");

    FileOutputStream byteWriter = null;
    FileInputStream reader = null;
    try {

        byteWriter = new FileOutputStream(fileName);
        reader = new FileInputStream(this.encodeFileName);

        while (reader.available() > 0) {
            letter = (char) reader.read();

            code += hCode.get(letter);

            if (code.length() > 7) {
                int c = Integer.parseInt(code.substring(0, 8), 2)
                        + Byte.MIN_VALUE;
                byteWriter.write((byte) c);
                code = code.substring(8);
            }
        }

        if (code.length() > 0 && code.length() <= 7) {
            code += "0000000";
            int c = Integer.parseInt(code.substring(0, 8), 2)
                    + Byte.MIN_VALUE;
            byteWriter.write((byte) c);
        }
        byteWriter.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
    System.out.println("===============================");
    System.out.println("File Created: " + fileName);

} 

我的錯誤總是出現在這一行:

int c = Integer.parseInt(code.substring(0, 8), 2)
                        + Byte.MIN_VALUE;

我得到的特定錯誤是:線程“ AWT-EventQueue-0”中的異常java.lang.NumberFormatException:對於輸入字符串:“ 110001nu”。 我不明白為什么換行符會導致此問題。 任何幫助將非常感激。

也許你hCode地圖不包含新行“信”的條目,所以hCode.get(letter)返回“空”,前兩個字母,其中你得到code.substring(0, 8)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM