在Java 9中,transferTo()方法已添加到InputStream 类中。该方法已用于在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 = "nhooo".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