如何在 Java 中将输入流连接到输出流?
How to connect a input stream to a output stream in Java?
有一个 InputStream 和一个 OutputStream。
我想连接它们。
我想做的是从InputStream中读取数据。
然后使用 OutputStream 输出相同的数据。
这是我的代码。
byte[] b = new byte[8192];
while((len = in.read(b, 0, 8192)) > 0){
out.write(b, 0, len);
}
有什么连接方法吗?
或者有什么办法可以不用buffer输入输出数据吗?
输入流和输出流都是被动对象,因此如果不创建线程将数据从一个对象复制到另一个对象,就无法连接它们。
注意:NIO 有一个 transferTo
方法,尽管它的功能大致相同,只是效率更高。
您不必使用缓冲区,但没有缓冲区可能会很慢。
Guava 和 Apache Commons 有复制方法:
ByteStreams.copy(input, output);
IOUtils.copy(input ,output);
他们不会直接 "connect" 他们。为了实现我假设你想要的,创建一个 InputStream
装饰器 class 写入 OutputStream
读取的所有内容。
你可以使用 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();
}
}
有一个 InputStream 和一个 OutputStream。
我想连接它们。
我想做的是从InputStream中读取数据。
然后使用 OutputStream 输出相同的数据。
这是我的代码。
byte[] b = new byte[8192];
while((len = in.read(b, 0, 8192)) > 0){
out.write(b, 0, len);
}
有什么连接方法吗?
或者有什么办法可以不用buffer输入输出数据吗?
输入流和输出流都是被动对象,因此如果不创建线程将数据从一个对象复制到另一个对象,就无法连接它们。
注意:NIO 有一个 transferTo
方法,尽管它的功能大致相同,只是效率更高。
您不必使用缓冲区,但没有缓冲区可能会很慢。
Guava 和 Apache Commons 有复制方法:
ByteStreams.copy(input, output);
IOUtils.copy(input ,output);
他们不会直接 "connect" 他们。为了实现我假设你想要的,创建一个 InputStream
装饰器 class 写入 OutputStream
读取的所有内容。
你可以使用 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();
}
}