我惊奇地发现,今天我找不到任何简单的方法来用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);
}

当前回答

JDK使用相同的代码,因此似乎没有“更简单”的方法,没有笨重的第三方库(可能不会做任何不同的事情)。下面是直接从java.nio.file.Files.java中复制的:

// buffer size used for reading and writing
private static final int BUFFER_SIZE = 8192;

/**
  * Reads all bytes from an input stream and writes them to an output stream.
  */
private static long copy(InputStream source, OutputStream sink) throws IOException {
    long nread = 0L;
    byte[] buf = new byte[BUFFER_SIZE];
    int n;
    while ((n = source.read(buf)) > 0) {
        sink.write(buf, 0, n);
        nread += n;
    }
    return nread;
}

其他回答

我认为这是可行的,但一定要测试一下……轻微的“改进”,但可能会以可读性为代价。

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

PipedInputStream和PipedOutputStream可能会有一些用处,因为您可以将其中一个连接到另一个。

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

正如Javadoc所指出的那样,PipedInputStream和PipedOutputStream只能在有多个线程时使用。

另外,请注意输入流和输出流不会用ioexception包装任何线程中断…所以,你应该考虑在你的代码中加入中断策略:

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

如果您希望使用这个API复制大量数据,或者从流中复制长时间无法忍受的数据,那么这将是一个有用的补充。

简单的函数

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

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();
    }
}