Dmitriy R
Dmitriy R

Reputation: 613

Copying InputStreamReader

Can somebody provide a source of

public class CopyingInputStreamReader extends InputStreamReader {
   public  CopyingInputStreamReader(InputStream is, OutputStream copyStream) {
  .....

The implementation should copy whatever got read to output stream. I have my implementation, but my HD crashed, so I need to recover it. Please respond in next 5 minutes, otherwise I will figure ot myself.

Upvotes: 0

Views: 1137

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503479

Personally I wouldn't do this at the reader level. I would write an InputStream which overrides all the methods methods from InputStream, delegating to the input stream that's been passed to the constructor and writes to the output stream after each read, before returning the data to the caller. For example:

@Override
public int read(byte[] buffer, int start, int length) throws IOException
{
    int ret = input.read(buffer, start, length);
    output.write(buffer, start, ret);
    return ret;
}

The reason I wouldn't make at extend InputStreamReader is that the results of all the read operations would be text data - which you'd then need to write to your OutputStream somehow...

Of course, if you really want to convert from one encoding to another, it would be worth extending Reader instead of InputStream, take another Reader to delegate to and a Writer to write to. Again, then you stay within one realm (text) instead of being part of the conversion yourself.

EDIT: It strikes me that I forgot to mention you also need to override the non-read methods to either just delegate directly to the input stream, or throw an exception. (For example, you probably don't want to support mark/reset.)

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533870

Use IOUtils with

IOUtils.copy(inputStream, outputStream);

Upvotes: 2

Related Questions