首頁  >  文章  >  Java  >  在Java 9中,transferTo()方法的重要性是什麼?

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

WBOY
WBOY轉載
2023-08-31 16:57:021081瀏覽

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

Java 9 中的 InputStream  類別中新增了 transferTo() 方法。此方法已用於複製Java 中從輸入流到輸出流的資料。這意味著它從輸入流中讀取所有字節,並按照讀取的順序將位元組寫入輸出流。

語法

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

範例

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();
   }
}

輸出

<strong>true</strong>

以上是在Java 9中,transferTo()方法的重要性是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除