程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

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

发布于2023-03-30 18:56     阅读(241)     评论(0)     点赞(11)     收藏(0)


我基本上在一个项目中有这些代码行,它们将输入流复制到输入流读取器中,以便它可以独立流式传输:

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调用放在首位,方法调用作为第一个参数。这是你问题的第一部分......



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/666429/ec641bded5bbc379e1a3/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

11 0
收藏该文
已收藏

评论内容:(最多支持255个字符)