FileInputStream in = new FileInputStream(myFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Run Code Online (Sandbox Code Playgroud)
问:我怎样才能读到的一切,从in进入out的方式是不是一个手工制作的循环用我自己的字节的缓冲区?
Jon*_*eet 34
编写一个方法来执行此操作,并从需要该功能的所有地方调用它.Guava已经有了这个代码ByteStreams.copy.我确信任何其他具有"通用"IO功能的库也有,但是Guava是我的第一个"首选"库.它摇滚:)
Sea*_*oyd 20
在Apache Commons/IO中,您可以使用以下命令IOUtils.copy(in, out):
InputStream in = new FileInputStream(myFile);
OutputStream out = new ByteArrayOutputStream();
IOUtils.copy(in, out);
Run Code Online (Sandbox Code Playgroud)
但我同意Jon Skeet,我宁愿使用Guava的 ByteStreams.copy(in, out)
Ole*_*.V. 18
Java 9(及更高版本)回答:
in.transferTo(out);
Run Code Online (Sandbox Code Playgroud)
似乎他们终于意识到这个功能是如此普遍需要它最好内置.该方法返回你需要知道的字节数.
小智 11
那么Guava的ByteStreams.copy(in,out)是做什么的:
private static final int BUF_SIZE = 0x1000; // 4K
public static long copy(InputStream from, OutputStream to)
throws IOException {
checkNotNull(from);
checkNotNull(to);
byte[] buf = new byte[BUF_SIZE];
long total = 0;
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
total += r;
}
return total;
}
Run Code Online (Sandbox Code Playgroud)
在我的项目中,我使用了以下方法:
private static void copyData(InputStream in, OutputStream out) throws Exception {
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27088 次 |
| 最近记录: |