本文共 2745 字,大约阅读时间需要 9 分钟。
本文翻译自:
I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream
to an OutputStream
in Java. 今天我很惊讶地发现,我无法找到将InputStream
的内容写入Java中的OutputStream
任何简单方法。 Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer). 显然,字节缓冲区代码并不难写,但我怀疑我只是遗漏了一些会让我的生活更轻松(代码更清晰)的东西。
So, given an InputStream
in
and an OutputStream
out
, is there a simpler way to write the following? 因此,给定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);}
参考:
Another possible candidate are the Guava I/O utilities: 另一个可能的候选者是Guava I / O实用程序:
I thought I'd use these since Guava is already immensely useful in my project, rather than adding yet another library for one function. 我以为我会使用这些,因为Guava在我的项目中已经非常有用,而不是为一个函数添加另一个库。
I think it's better to use a large buffer, because most of the files are greater than 1024 bytes. 我认为最好使用大缓冲区,因为大多数文件大于1024字节。 Also it's a good practice to check the number of read bytes to be positive. 另外,最好将读取的字节数检查为正数。
byte[] buffer = new byte[4096];int n;while ((n = in.read(buffer)) > 0) { out.write(buffer, 0, n);}out.close();
If you only need this for writing an InputStream
to a File
then you can use this simple function: 如果您只需要这个来将InputStream
写入File
那么您可以使用这个简单的函数:
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(); }}
If you are using Java 7, (in the standard library) is the best approach: 如果您使用的是Java 7,则 (在标准库中)是最佳方法:
/* You can get Path from file also: file.toPath() */Files.copy(InputStream in, Path target)Files.copy(Path source, OutputStream out)
Edit: Of course it's just useful when you create one of InputStream or OutputStream from file. 编辑:当然,从文件创建一个InputStream或OutputStream时它非常有用。 Use file.toPath()
to get path from file. 使用file.toPath()
从文件中获取路径。
To write into an existing file (eg one created with File.createTempFile()
), you'll need to pass the REPLACE_EXISTING
copy option (otherwise FileAlreadyExistsException
is thrown): 要写入现有文件(例如,使用File.createTempFile()
创建的文件),您需要传递REPLACE_EXISTING
复制选项(否则抛出FileAlreadyExistsException
):
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)
Use Commons Net's Util class: 使用Commons Net的Util类:
import org.apache.commons.net.io.Util;...Util.copyStream(in, out);
转载地址:http://ubexb.baihongyu.com/