简体   繁体   English

霍夫曼编码文件保存

[英]Huffman coding file saving

I wrote a program that uses huffman coding to take a .txt file and compress it. 我编写了一个使用霍夫曼编码的程序,以获取一个.txt文件并将其压缩。 The program takes the compressed code and saves it as a .hzip file. 该程序将压缩的代码保存为.hzip文件。 The code works fine until I try to compress and save a file that contains a new line character. 在我尝试压缩并保存包含换行符的文件之前,代码可以正常工作。 This is my code to save the file: 这是我保存文件的代码:

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);

} 

My error always comes up on this line: 我的错误总是出现在这一行:

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

The specific error I am getting is: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "110001nu". 我得到的特定错误是:线程“ AWT-EventQueue-0”中的异常java.lang.NumberFormatException:对于输入字符串:“ 110001nu”。 I don't understand why a new line character is causing this problem. 我不明白为什么换行符会导致此问题。 Any help would be much appreciated. 任何帮助将非常感激。

也许你hCode地图不包含新行“信”的条目,所以hCode.get(letter)返回“空”,前两个字母,其中你得到code.substring(0, 8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM