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

当前回答

试试Cactoos:

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

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

其他回答

另一个可能的候选程序是Guava I/O实用程序:

http://code.google.com/p/guava-libraries/wiki/IOExplained

我认为我应该使用这些库,因为Guava在我的项目中已经非常有用,而不是为一个函数添加另一个库。

简单的函数

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

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

我认为最好使用一个大的缓冲区,因为大多数文件都大于1024字节。另外,检查读取字节数是否为正也是一个很好的做法。

byte[] buffer = new byte[4096];
int n;
while ((n = in.read(buffer)) > 0) {
    out.write(buffer, 0, n);
}
out.close();

如果你正在使用Java 7,文件(在标准库中)是最好的方法:

/* You can get Path from file also: file.toPath() */
Files.copy(InputStream in, Path target)
Files.copy(Path source, OutputStream out)

编辑:当然,当你从文件中创建一个InputStream或OutputStream时,它才有用。使用file. topath()从文件中获取路径。

要写入一个现有的文件(例如用file . createtempfile()创建的文件),你需要传递REPLACE_EXISTING复制选项(否则会抛出FileAlreadyExistsException):

Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)

一个IMHO更小的代码片段(也更狭窄地作用于长度变量):

byte[] buffer = new byte[2048];
for (int n = in.read(buffer); n >= 0; n = in.read(buffer))
    out.write(buffer, 0, n);

顺便说一句,我不明白为什么更多的人不使用for循环,而是选择一段时间使用被一些人视为“糟糕”风格的赋值-测试表达式。