FilterOutputStream的用法 [英] Usage of FilterOutputStream

查看:169
本文介绍了FilterOutputStream的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中 FilterOutputStream 的实际用法是什么?
来自javadocs:

What is practical usage of FilterOutputStream in Java? From javadocs:


此类是过滤输出流的所有类的超类。这些流位于已经存在的输出流(基础输出流)之上,它将其用作数据的基本接收器,但可能会沿途转换数据或提供其他功能。

This class is the superclass of all classes that filter output streams. These streams sit on top of an already existing output stream (the underlying output stream) which it uses as its basic sink of data, but possibly transforming the data along the way or providing additional functionality.

对我而言,似乎有与 OutputStream 相同的方法(可能由于某种原因覆盖了它们?)。它提供了什么样的数据转换以及什么时候可以在自己的Java应用程序中使用它?

For me it seems to have same methods as OutputStream (maybe it overrides them for some reason?). What kind of data "transformation" does it offer and when can one use it in own Java application?

推荐答案

有效Java项目16中的Joshua Bloch:赞成继承继承解释了为什么继承并不总是最好的工具。使用Decorator模式通常更有效。 FilterOutputStream和FilterInputStream是实现此模式的基础。例如,我想阻止OutputStream.close。这就是我能做的事情

Joshua Bloch in Effective Java Item 16: Favor composition over inheritance explains why inheritance is not always the best tool for the job. It is often more efficient to use Decorator pattern. FilterOutputStream and FilterInputStream are the base for implementing this pattern. For example I want to block OutputStream.close. This is what I could do

class NonCloseableOutputStream extends FilterOutputStream {

    public NonCloseableOutputStream(OutputStream out) {
        super(out);
    }

    @Override
    public void close() throws IOException {
        // ignore
    }
}

现在我的类可以接受OutputStream的任何子类并使其不可关闭。

Now my class can accept any subclass of OutputStream and make it non-closeable.

这篇关于FilterOutputStream的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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