将 PrintWriter 与另一个 PrintWriter 进行比较
我有两个 PrintWriter:
PrintWriter pw1 = new PrintWriter("testPrint.txt");
PrintWriter pw2 = new PrintWriter("testPrint.txt");
我想检查它们是否都打印到同一个文件,但与
pw1.equals(pw2)
或
Objects.equals(pw1, pw2)
进行比较不起作用。另外,我希望能够检查像这两个这样的 PrintWriters 是否打印到同一个地方,而不是带有文件路径的 String:
PrintWriter pw1 = new PrintWriter(System.out, true);
PrintWriter pw2 = new PrintWriter(System.out, true);
有没有办法做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不是您写的两个印刷作家。通常,有两个作家写信到同一目的地是您应该避免的问题。相反,如果您想将多个源编写到同一文件,请使用一个打印稿和一条编写的消息队列。
您可能还需要查看可以锁定的Filechannel。请参阅:
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?
无法从外部检查
PrintWriter
的底层流。有一个out
成员变量 但它是一个受保护的属性,只能由子类访问。即使您有权访问该字段,它仍然不像比较两个实例那么容易。两个底层写入器可能是写入同一位置的不同对象。这正是当您使用
PrintWriter(String)
构造函数:它将创建两个
BufferedWriter
,它们指向不同的OutputStreamWriter
>s,它将指向不同的FileOutputStream
。一路下来都是乌龟。There's no way from the outside to check a
PrintWriter
's underlying stream. There is anout
member variable but it's a protected property only accessible by subclasses.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:It would create two
BufferedWriter
s, which would point to distinctOutputStreamWriter
s, which would point to distinctFileOutputStream
s. It's turtles all the way down.