Home > other >  Java try with resources with Reader and Writer on the same file
Java try with resources with Reader and Writer on the same file

Time:04-28

try (Reader reader = Files.newBufferedReader(path);
     Writer writer = Files.newBufferedWriter(path)) {
    ...
} catch (IOException exception) {
    ...
}

Can I use Reader and Writer which open the same file in try-with-resources? Is it safe?

CodePudding user response:

Even if it's allowed, it's just waiting for problems to occur. Reader and Writer are not meant to work on the same file.

There are alternatives that you can look into. Good old RandomAccessFile is created to support both reading and writing. It's not great for text though. FileChannel, accessible from a RandomAccessFile or using FileChannel.open is newer but still doesn't work well with text.

CodePudding user response:

This would be a bad practice. Different operating system will give you inconsistent results and it's asking for problems.

You'd be better off reading the file, writing to a temporary file, then replacing the old file with the temporary file when you're done.

  • Related