Home  >  Article  >  Java  >  What is the importance of transferTo() method in Java 9?

What is the importance of transferTo() method in Java 9?

WBOY
WBOYforward
2023-08-31 16:57:021122browse

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

The transferTo() method was added to the InputStream class in Java 9. This method has been used to copy data from an input stream to an output stream in Java. This means that it reads all bytes from the input stream and writes the bytes to the output stream in the order they were read.

Syntax

<strong>public long transferTo(OutputStream out) throws IOException</strong>

Example

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".<strong>getBytes()</strong>;
      <strong>ByteArrayInputStream </strong>bis = new ByteArrayInputStream(inBytes);
      <strong>ByteArrayOutputStream </strong>bos = new ByteArrayOutputStream();
      try {
         bis.<strong>transferTo</strong>(bos);
         byte[] outBytes = bos.<strong>toByteArray</strong>();
         System.out.println(<strong>Arrays.equals(</strong>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();
   }
}

Output

<strong>true</strong>

The above is the detailed content of What is the importance of transferTo() method in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete