简体   繁体   中英

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

I basically have in a project these lines of code which copies an input stream into an input stream reader so it can be streamed independently:

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");

It is working fine but I would like to encapsulate this code into an object, for instance an "InputStreamReaderCopy", which would extend InputStreamReader so it can be used exactly like it.

I wanted first to code something like this:

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);
    }
}

But as you might expect, it is not possible to call super() after something else in the constructor.

I finally ended by having a private member

private InputStreamReader reader;

And using delegate methods of InputStreamReader and calling these king of things

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

The problem of that is that I need to call

super(inputStream);

In the first line of my constructor even if does not make any sense (as all overidden methods are calling methods of the private member). Is there any way to make this code more elegant ? Should I simply avoid extending InputStreamReader ?

IMPLEMENTATION OF ANSWER BY @maxime.bochon (that suits me well)

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");
    }
}

Try to put the code creating the InputStream in a private static method. You should then be able to put the super call in first place with a method call as a first parameter. This is for the first part of your question...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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