0

I am a computer science student - second year. I was asked to prepare a project - by Hoffman Code. During the project I got stuck in the fault, I am in the project phase building the encoder. I get a file - and I have to encode it in bytes - according to the Hoffman code.

My question is how to encode the file in bytes - what I did: for example: I received the word "abca cadbara" in the file. And into another file I put the encoding but using a string and not in bytes.

the part of the code:

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

How can I use bytes and not the string? Thanks for the help.

  • `String` instances have method `getBytes()` - is it ok for you? – Nowhere Man May 15 '20 at 17:50
  • Does this answer your question? [How to convert string back to bytes in order to write to file in Java?](https://stackoverflow.com/questions/36583552/how-to-convert-string-back-to-bytes-in-order-to-write-to-file-in-java) – Arvind Kumar Avinash Jun 23 '20 at 09:48

1 Answers1

0
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. Use String.getBytes() to write bytes to the file.
  2. Use try-with-resources and don't worry about closing the resources. Use ; to separate multiple resources.
  3. Don't write in a loop. Build the string first and then write it once. I/O is slow.
  4. When concatenating in a loop, use StringBuilder avoid creating new Strings.
  5. I made your code a bit more concise, you can rewrite as you like.
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43