我惊奇地发现,今天我找不到任何简单的方法来用Java将InputStream的内容写入OutputStream。显然,编写字节缓冲区代码并不难,但我怀疑我只是缺少了一些可以使我的工作更简单(并且代码更清晰)的东西。

那么,给定一个InputStream in和一个OutputStream out,是否有一种更简单的方法来编写下面的代码?

byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
}

当前回答

下面是我如何使用最简单的for循环。

private void copy(final InputStream in, final OutputStream out)
    throws IOException {
    final byte[] b = new byte[8192];
    for (int r; (r = in.read(b)) != -1;) {
        out.write(b, 0, r);
    }
}

其他回答

简单的函数

如果你只需要将输入流写入文件,那么你可以使用这个简单的函数:

private void copyInputStreamToFile( InputStream in, File file ) {
    try {
        OutputStream out = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len;
        while((len=in.read(buf))>0){
            out.write(buf,0,len);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

试试Cactoos:

new LengthOf(new TeeInput(input, output)).value();

更多详情请访问:http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html

可读性不是很好,但是很有效,没有依赖关系,可以在任何java版本上运行

byte[] buffer=new byte[1024];
for(int n; (n=inputStream.read(buffer))!=-1; outputStream.write(buffer,0,n));

使用JDK方法无法更容易地做到这一点,但正如Apocalisp已经指出的那样,你不是唯一一个有这种想法的人:你可以使用Jakarta Commons IO中的IOUtils,它还有许多其他有用的东西,IMO实际上应该是JDK的一部分……

这是我最好的机会!!

不要使用inputStream.transferTo(…),因为它太通用了。 如果你能控制你的缓冲内存,你的代码性能会更好。

public static void transfer(InputStream in, OutputStream out, int buffer) throws IOException {
    byte[] read = new byte[buffer]; // Your buffer size.
    while (0 < (buffer = in.read(read)))
        out.write(read, 0, buffer);
}

当我提前知道流的大小时,我使用这种(可改进的)方法。

public static void transfer(int size, InputStream in, OutputStream out) throws IOException {
    transfer(in, out,
            size > 0xFFFF ? 0xFFFF // 16bits 65,536
                    : size > 0xFFF ? 0xFFF// 12bits 4096
                            : size < 0xFF ? 0xFF // 8bits 256
                                    : size
    );
}