Search code examples
javafilebinaryfiles

How to read binary files in a string sequence of 1 and 0?


I've created a Huffman coding algorithm, and then I wrote binary code in String and put it in binary file using FileOutputStream and DataOutputStream.

But now I cant understand how to read it? I need to get 1 and 0 sequence from binary file.

There is no method like .readString() in DataInputStream

try{
    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary", "*.bin"));
    FileOutputStream fileOutputStream = new FileOutputStream(fileChooser.showSaveDialog(window));
    DataOutputStream outputStream = new DataOutputStream(fileOutputStream);
    outputStream.writeChars(Main.string_ready_encode);
}catch (IOException e){
    e.printStackTrace();
}

Main.string_ready_encode contains ready sequence


Solution

  • The problem with your writing code is that you have specified no file format. We now can only read the file if we know how many bytes it has. If you do know that, you can read it by doing the following:

    try (DataInputStream stream = new DataInputStream(new FileInputStream(f))) {
        byte[] bytes = new byte[NUMBER_OF_BYTES];
        stream.read(bytes);
        String content = new String(bytes);
        System.out.println(content);
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    But I would actually advise you to rewrite you file with some known file format, like so:

    try (Writer writer = new OutputStreamWriter(new FileOutputStream(f), Charsets.UTF_8)) {
        writer.write(Main.stringReadyEncode, 0, Main.stringReadyEncode.length());
    } catch (IOException x) {
        e.printStackTrace();
    }
    

    And read it like you would read any other file:

    try (BufferedReader r = Files.newBufferedReader(f.toPath(), Charsets.UTF_8)) {
        String line;
        while((line = r.readLine()) != null) {
            // do whatever you want with line
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    Just make sure to replace Charsets.UTF_8 with whatever encoding you used while writing to the file.