Reputation: 1661
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?
Upvotes: 0
Views: 2779
Reputation: 2021
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.
Upvotes: 1
Reputation: 27958
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();
}
}
Upvotes: -1
Reputation: 533432
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.
Upvotes: 1