Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Tầm quan trọng của phương thức transferTo() của InputStream trong Java 9

Phương thức transferTo() đã được thêm vào lớp InputStream trong Java 9. Phương thức này dùng để sao chép dữ liệu từ input stream sang output stream. Nó đọc tất cả byte từ input stream và ghi các byte đó vào output stream theo thứ tự đọc.

Cú pháp

public long transferTo(OutputStream out) throws IOException

Ví dụ minh họa

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

Kết quả

true

Phương thức trả về true xác nhận dữ liệu được chuyển toàn vẹn từ input stream sang output stream.