七、Channel-to-Channel传输
FileChannel类有这两个独有的方法方法:transferFrom()和testTransferTo(),因此Channel-to-Channel传输中通道之一必须是FileChannel。
直接的通道传输不会更新与某个FileChannel关联的position值。
对于传输数据来源是一个文件的transferTo()方法,如果position + count的值大于文件的size值,传输会在文件尾的位置终止。
[java] view plain copy
-
-
-
- @org.junit.Test
- public void testTransferFrom() throws Exception{
-
-
-
- RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
- FileChannel fromChannel = fromFile.getChannel();
-
-
-
-
- RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
- FileChannel toChannel = toFile.getChannel();
-
-
-
-
- long position = 0;
- long count = fromChannel.size();
-
-
-
-
- toChannel.transferFrom(fromChannel, position, count);
-
- toChannel.close();
- toFile.close();
- fromChannel.close();
- fromFile.close();
- }
[java] view plain copy
-
-
-
- @org.junit.Test
- public void testTransferTo() throws Exception{
-
-
-
- RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
- FileChannel fromChannel = fromFile.getChannel();
-
-
-
-
- WritableByteChannel toChannel = Channels.newChannel(System.out);
-
-
-
-
- fromChannel.transferTo(0, fromChannel.size(), toChannel);
- fromChannel.close();
- fromFile.close();
- }