Java 9 中 InputStream 的 transferTo() 方法的重要性是什么?


在 Java 9 中,InputStream 类中增加了 transferTo() 方法。此方法用于在 Java 中 将数据从输入流复制到输出流。这意味着它会从输入流中读取所有字节,然后按读取顺序将这些字节写入输出流。

语法

public long transferTo(OutputStream out) throws IOException

示例

import java.util.Arrays;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class TransferToMethodTest {
   public void testTransferTo() throws IOException {
      byte[] inBytes = "tutorialspoint".getBytes();
      ByteArrayInputStream bis = new ByteArrayInputStream(inBytes);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      try {
         bis.transferTo(bos);
         byte[] outBytes = bos.toByteArray();
         System.out.println(Arrays.equals(inBytes, outBytes));
      } finally {
         try {
            bis.close();
         } catch(IOException e) {
            e.printStackTrace();
         }
         try {
            bos.close();
         } catch(IOException e) {
              e.printStackTrace();
         }
      }
   }
   public static void main(String args[]) throws Exception {
      TransferToMethodTest test = new TransferToMethodTest();
      test.testTransferTo();
   }
}

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

true

更新于: 26-Feb-2020

1K+ 访问量

启动您的职业生涯

完成课程以获得认证

开始
广告