Search code examples
javainputstreambufferedreaderoutputstream

Using Files API to read and write to .txt file, not the same as using BufferredWriter?


I am doing the Text Editor project on Hyperskill and all is well except stage two test #18. I paid my gems to see the solution to this and I can't understand what the differnece is between my code and the successful code. I'm hoping someone can explain why it works and mine doesn't?

The error I get is; "Text should be the same after saving and loading same file"

As far as I can see it is the same. I select all text with CTRL-A (In the JTextArea)and it selects the line breaks and spaces.

I cannot see what the difference is between my code and some correct solutions that pass the test. My code does what is required and input / output is in bytes, which should gather any white space characters or line breaks, right?

Can anyone tell me what the ultimate difference is between (save to file method) my unsuccessful code -

try {
        Files.write(Path.of("./"
                            + textField.getText()),                     
                            textArea.getText().getBytes());
} catch (IOException ioException) {
        ioException.printStackTrace();
}

This is writing to the file in bytes, is it not? Compared to the successful code -

String content = textArea.getText();
try (final BufferedWriter writer = 
             Files.newBufferedWriter(Path.of("./"
                            + textField.getText()));) {
        writer.write(content);
        writer.flush();
} catch (IOException ioException) {
        System.out.println("Cant save file" + ioException);
}

For reading a file, my unsuccessful code is -

try {
         String content = new String(Files.readAllBytes(Path.of("./"
                                            + textField.getText())));
         textArea.setText(content);
} catch (IOException ioException) {
         ioException.printStackTrace();
}

The successful code is -

try {
         textArea.setText(new String(Files.readAllBytes(Paths.get(path))));
} catch (IOException e) {
         System.out.println("Cant read file!!!");
         return null;
}

What is the difference? I am using Files in a slightly different way but I can only see that it is getting bytes to strings or vice versa.


Solution

  • If we assume that your path names are correct, then it's possible the two different write methods are using different codecs.

    String#getBytes uses the platform default charset.

    Files.newBufferedWriter uses UTF8.

    So if your platform default is not utf8 then you could be writing different bytes. Maybe try.

    string.getBytes(StandardCharsets.UTF_8);