Home > Mobile >  Comparing a PrintWriter to another PrintWriter
Comparing a PrintWriter to another PrintWriter

Time:03-28

I have two PrintWriters:

PrintWriter pw1 = new PrintWriter("testPrint.txt");
PrintWriter pw2 = new PrintWriter("testPrint.txt");

I want to to check if both of them print to the same file, but comparing with

pw1.equals(pw2)

or

Objects.equals(pw1, pw2)

doesn't work. Also, instead of String with a path to file I want to be able to check if PrintWriters like those two print to the same place in general:

PrintWriter pw1 = new PrintWriter(System.out, true);
PrintWriter pw2 = new PrintWriter(System.out, true);

Is there a way to do that?

CodePudding user response:

No, not from two Print writers as you have written it. In general, having two writers writing to the same destination is a problem you should avoid. Instead, if you want multiple sources writing to the same file, use one PrintWriter and a queue of messages to be written.

You may also want to check out FileChannel, which can be locked. See: can we open multiple FileWriter stream to the same file at the same time?

CodePudding user response:

There's no way from the outside to check a PrintWriter's underlying stream. There is an out member variable but it's a protected property only accessible by subclasses.

protected Writer out

The underlying character-output stream of this PrintWriter.

Even if you had access to this field, though, it still wouldn't be as easy as comparing two instances. The two underlying writers could be different objects that write to the same place. That is exactly what will happen when you use the PrintWriter(String) constructor from your first example:

package java.io;

public class PrintWriter extends Writer {
    // ...

    public PrintWriter(String fileName) throws FileNotFoundException {
        this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
             false);
    }

    // ...
}

It would create two BufferedWriters, which would point to distinct OutputStreamWriters, which would point to distinct FileOutputStreams. It's turtles all the way down.

  • Related