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();
}
}輸出
true
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP