繁体   English   中英

扩展InputStreamReader行为的最有效方法是什么?

[英]What is the most efficient way to extend the behaviour of InputStreamReader?

我基本上在项目中有以下几行代码,它们将输入流复制到输入流读取器中,以便可以独立地进行流传输:

final InputStream stream = new InputStream(this.in);    
ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(stream, baos);
InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
baos.close();
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");

它工作正常,但是我想将此代码封装到一个对象中,例如“ InputStreamReaderCopy”,它将扩展InputStreamReader以便可以像使用它一样使用。

我想先编写如下代码:

public class InputStreamReaderCopy extends InputStreamReader {
    public InputStreamReaderCopy(InputStream inputStream, String encoding) throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(inputStream, baos);
        InputStream newInputStream = new ByteArrayInputStream(baos.toByteArray());
        baos.close();
        super(newInputStream, encoding);
    }
}

但是,正如您可能期望的那样,不可能在构造函数中的其他函数之后调用super()。

最后我有了一个私人会员

private InputStreamReader reader;

并使用InputStreamReader的委托方法并调用这些事物之王

@Override
public int read(CharBuffer target) throws IOException {
    return reader.read(target);
}

问题是我需要打电话

super(inputStream);

在我的构造函数的第一行中,即使没有任何意义(因为所有隐藏的方法都在调用私有成员的方法)。 有什么办法可以使此代码更优雅? 我应该避免扩展InputStreamReader吗?

@ maxime.bochon的答案实施(非常适合我)

public class InputStreamReaderCopy extends InputStreamReader {

    private static InputStream createInputStreamCopy(InputStream inputStream )throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(inputStream, baos);
        InputStream newInputStream = new ByteArrayInputStream(baos.toByteArray());
        baos.close();
        return newInputStream;
    }

    public InputStreamReaderCopy(InputStream inputStream) throws IOException{
        super(createInputStreamCopy(inputStream), "UTF-8");
    }
}

尝试将创建InputStream的代码放在private static方法中。 然后,您应该能够将super调用放在首位,并将方法调用作为第一个参数。 这是您问题的第一部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM