You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 10中java.io.Reader的transferTo方法是什么?InputStream有同类方法吗?

Java字节流的便捷复制方法:InputStream.transferTo()

好问题!确实,Reader.transferTo()在字符流场景下帮我们省去了手动写循环复制的麻烦,那字节流这边的InputStream和OutputStream有没有对应的便捷方法呢?答案是有的,不过要看你使用的Java版本:

Java 9及以上版本:原生支持InputStream.transferTo()

从Java 9开始,InputStream类新增了transferTo(OutputStream out)方法,它的作用和Reader.transferTo()完全对应——从输入流读取所有字节,并按读取顺序写入指定的输出流,还会返回实际传输的字节总数。

用起来非常简单,示例代码如下:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class StreamCopyExample {
    public static void main(String[] args) {
        // 使用try-with-resources自动关闭流资源
        try (InputStream in = new FileInputStream("source.file");
             OutputStream out = new FileOutputStream("target.file")) {
            long transferredBytes = in.transferTo(out);
            System.out.println("成功传输 " + transferredBytes + " 字节");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这个方法内部已经帮我们处理了缓冲区的逻辑,不用再手动写read()和write()的循环,代码简洁很多。

Java 8及更早版本:手动实现或借助工具库

如果你的项目还在使用Java 8或更早的版本,原生InputStream没有transferTo()方法,这时候有两种选择:

  1. 手动实现缓冲区循环:这是最基础的方式,示例代码如下:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class LegacyStreamCopy {
    public static void main(String[] args) {
        byte[] buffer = new byte[8192]; // 8KB缓冲区是常用的合理大小
        int bytesRead;
        try (InputStream in = new FileInputStream("source.file");
             OutputStream out = new FileOutputStream("target.file")) {
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 借助第三方工具库:比如Apache Commons IO的IOUtils.copy(InputStream, OutputStream)方法,它封装了类似的逻辑,引入依赖后直接调用即可,代码更简洁。

总结

如果你使用的是Java 9或更高版本,直接用InputStream.transferTo()就可以实现字节流的便捷复制,和Reader.transferTo()的体验一致;如果是旧版本Java,要么手动写循环,要么借助工具库来简化代码。

内容的提问来源于stack exchange,提问作者Shubham Kadlag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:12:42