【问题标题】:huffman code encoder - Write to output file霍夫曼代码编码器 - 写入输出文件
【发布时间】:2020-05-15 17:16:36
【问题描述】:

我是一名计算机科学专业的学生 - 二年级。霍夫曼代码要求我准备一个项目。 在项目期间,我陷入了故障,我正处于构建编码器的项目阶段。我得到了一个文件——我必须按照 Hoffman 代码将它编码为字节。

我的问题是如何以字节为单位对文件进行编码 - 我做了什么:例如: 我在文件中收到了“abca cadbara”这个词。并在另一个文件中放入编码,但使用字符串而不是字节。

部分代码:

    public static void writeOutputFile (String[] input_names, String[] output_names, Map<Character, String> codes)
    {
        FileInputStream input;
        FileOutputStream output;
        try
        {
            input = new FileInputStream(input_names[0]);
            output = new FileOutputStream(output_names[0]);

            for (int i = 0; i < (int) input.getChannel().size(); i++)   
            {

                int x = input.read();
                String codeOutput = codes.get((char) x);
                //output.write(Integer.parseInt(codeOutput, 2));
                for (int j = 0; j < codeOutput.length(); j++) {
                    output.write((int) codeOutput.charAt(j));
                }
            }

            input.close();
            output.close();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

如何使用字节而不是字符串? 感谢您的帮助。

【问题讨论】:

标签: java


【解决方案1】:
public static void writeOutputFile (String[] input_names, 
                                    String[] output_names, 
                                    Map<Character, String> codes) {

    try (FileInputStream input = new FileInputStream(input_names[0]);
        FileOutputStream output = new FileOutputStream(output_names[0])) {

        StringBuilder toWrite = new StringBuilder();
        for (int i = 0; i < (int) input.getChannel().size(); i++) {
            toWrite.append(codes.get((char) input.read()));
        }
        output.write(toWrite.toString().getBytes());

    } catch (IOException e) {
        e.printStackTrace();
    }
}
  1. 使用String.getBytes() 将字节写入文件。
  2. 使用try-with-resources,不用担心关闭资源。使用; 分隔多个资源。
  3. 不要循环写入。首先构建字符串,然后编写一次。 I/O 很慢。
  4. 在循环中连接时,使用StringBuilder 避免创建新字符串。
  5. 我让你的代码更简洁了,你可以随意重写。

【讨论】:

    猜你喜欢
    • 2012-03-10
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多