0

Having a InputStream and a OutputStream.
I want to connect them.

What I want to do is reading data from InputStream.
And then output the same data by using OutputStream.
This is my code.

byte[] b = new byte[8192];
while((len = in.read(b, 0, 8192)) > 0){
    out.write(b, 0, len);
}

Is there any method to connect them?
Or is there any way to input and output data without buffer?

Larry Lu
  • 1,609
  • 3
  • 21
  • 28
  • Why are you doing this, is the pertinent question? There is [`PipedInput/OutputStream`](https://docs.oracle.com/javase/7/docs/api/java/io/PipedOutputStream.html) but this is for fairly advanced use cases where you need inter-thread communication. If you are just dumping data across on the same thread, then your approach is fine. Question is though - where is the `OutputStream` _going_... – Boris the Spider Mar 08 '16 at 13:57
  • @BoristheSpider using a piped stream will copy from an output to an input. – Peter Lawrey Mar 08 '16 at 13:58
  • Possible duplicate of [Connecting an input stream to an outputstream](http://stackoverflow.com/questions/1574837/connecting-an-input-stream-to-an-outputstream) – Software Engineer Mar 08 '16 at 14:03

3 Answers3

1

Both input and output streams are a passive objects, so there is no way to connect them without creating a Thread to copy the data from one to another.

Note: NIO has a transferTo method though it does much the same, just more efficiently.

You don't have to use a buffer but it likely to be very slow without one.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Guava and Apache Commons have copy methods:

ByteStreams.copy(input, output);

IOUtils.copy(input ,output);

They don't "connect" them directly. To achieve what I am assuming you want, create an InputStream decorator class that writes to an OutputStream everything that is read.

andrucz
  • 1,971
  • 2
  • 18
  • 30
-1

You could use a NIO channel/buffer

try (FileChannel in = new FileInputStream(inFile).getChannel();
     FileChannel out = new FileOutputStream(outFile).getChannel()) 
{
    ByteBuffer buff = ByteBuffer.allocate(8192);

    int len;
    while ((len = in.read(buff)) > 0) { 
        buff.flip();
        out.write(buff);
        buff.clear();
    }
} 
lance-java
  • 25,497
  • 4
  • 59
  • 101
  • But this way also need buffer. – Larry Lu Mar 08 '16 at 14:07
  • If you are using NIO anyway, why not just use [`FileChannel.transferTo/From`](https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#transferFrom(java.nio.channels.ReadableByteChannel,%20long,%20long))? It will more efficient, especially if it can ask the filesystem to do the transfer. – Boris the Spider Mar 08 '16 at 15:04