Java让PrintWriter编写两个不同的Writer [英] Java Make a PrintWriter write two different Writer's

查看:215
本文介绍了Java让PrintWriter编写两个不同的Writer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构一些代码并希望制作一个PrintWriter,它将输出发送到两个单独的Writer(不是流,它们最终会转到不同的地方,其中一个可能有其他东西从其他地方发送到它)。

I am refactoring some code and want to make a PrintWriter that will send output to two seperate Writer's (not streams, and they ultimately go different places, one of them may have other stuff sent to it from elsewhere).

对于流有Apache TeeOutputStream,有没有什么可供Writer使用,还是需要通过流然后返回文本?

For streams there is the Apache TeeOutputStream, is there anything for Writer or will I need to go via a stream and back to text?

推荐答案

标准Java库中没有这样的多写器,但您可以非常轻松地创建一个。 容易的原因是因为 java.io.Writer 中只有3个 abstract 方法: close() flush() write(char [] cbuf,int off,int len)

There is no such "multiwriter" in the standard Java library, but you can create one very easily. The reason for "easily" is because there are only 3 abstract methods in java.io.Writer: close(), flush() and write(char[] cbuf, int off, int len).

write()方法调用的所有其他重载的默认实现这个抽象的。

The default implementation of all other overloads of the write() method call this abstract one.

你只需要存储你想转发的作者并做到这一点:转发这三种抽象方法的调用:

You just have to store the writers you want to forward to and do just that: forward the calls of these 3 abstract methods:

class MultiWriter extends Writer {

    private final Writer[] writers;

    public MultiWriter(Writer... writers) {
        this.writers = writers;
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        for (Writer w : writers)
            w.write(cbuf, off, len);
    }

    @Override
    public void flush() throws IOException {
        for (Writer w : writers)
            w.flush();
    }

    @Override
    public void close() throws IOException {
        for (Writer w : writers)
            w.close();
    }

};

注意:

我知道你想要一个 PrintWriter ,但是因为我们的 MultiWriter 是一个 java。 io.Writer ,您可以直接将其传递给 PrintWriter ,如下所示:

I know you wanted a PrintWriter, but since our MultiWriter is a java.io.Writer, you can simply pass it to a PrintWriter like this:

PrintWriter pw = new PrintWriter(new MultiWriter(writer1, writer2));

注意#2:

在我的实现中,我没有捕获我们转发的作者抛出的异常。例如,如果子作者的 write()方法会产生 IOException ,即使我们成功要写入其他编写器,失败的编写器仍然会失败...如果我们想处理个别异常,我们必须实现一个新的 IOException 其他 IOException 的集合,因为多个子作者可能很容易失败。

In my implementation I did not catch exceptions thrown by the writers we forward to. If for example the write() method of a "child" writer would thow an IOException, even if we would succeed to write to other writers, the one that failed will still be failed... If we wanted to handle individual exceptions, we would have to implement a new IOException that could hold a collection of other IOException because multiple "child" writers could fail just as easily.

这篇关于Java让PrintWriter编写两个不同的Writer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆