java 如何拷贝流量
拷贝流量的方法
在Java中,拷贝流(InputStream到OutputStream)可以通过多种方式实现。以下是几种常见的方法:
使用InputStream.transferTo(Java 9及以上)
Java 9引入了InputStream.transferTo方法,可以高效地将输入流的内容传输到输出流。
try (InputStream in = new FileInputStream("source.txt");
OutputStream out = new FileOutputStream("destination.txt")) {
in.transferTo(out);
}
使用BufferedInputStream和BufferedOutputStream
通过缓冲流可以提高拷贝效率,适用于大文件或网络流。
try (InputStream in = new BufferedInputStream(new FileInputStream("source.txt"));
OutputStream out = new BufferedOutputStream(new FileOutputStream("destination.txt"))) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
使用Apache Commons IO
如果项目中已经引入了Apache Commons IO库,可以使用IOUtils.copy方法简化代码。
try (InputStream in = new FileInputStream("source.txt");
OutputStream out = new FileOutputStream("destination.txt")) {
IOUtils.copy(in, out);
}
使用Java NIO的Files.copy
对于文件流的拷贝,Java NIO的Files.copy方法是最简洁的方式。

Path source = Paths.get("source.txt");
Path destination = Paths.get("destination.txt");
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
注意事项
- 始终使用
try-with-resources确保流被正确关闭,避免资源泄漏。 - 对于大文件,使用缓冲流(如
BufferedInputStream)可以提高性能。 - 如果目标文件已存在,可能需要指定
StandardCopyOption.REPLACE_EXISTING覆盖文件。
以上方法适用于大多数场景,选择哪种方法取决于具体需求和Java版本。






