|
| 1 | +package com.brianway.java.nio.tutorial; |
| 2 | + |
| 3 | +import com.brianway.learning.java.nio.tutorial.BufferDemo; |
| 4 | +import org.junit.Assert; |
| 5 | +import org.junit.Test; |
| 6 | + |
| 7 | +import java.io.IOException; |
| 8 | +import java.io.RandomAccessFile; |
| 9 | +import java.nio.channels.FileChannel; |
| 10 | + |
| 11 | +/** |
| 12 | + * 通道之间的数据传输 |
| 13 | + * |
| 14 | + * @auther brian |
| 15 | + * @since 2019/6/19 00:20 |
| 16 | + */ |
| 17 | +public class ChannelTransferTest { |
| 18 | + private String fromPath = BufferDemo.class.getResource("/").getPath() + "fromFile.txt"; |
| 19 | + private String toPath = BufferDemo.class.getResource("/").getPath() + "toFile.txt"; |
| 20 | + |
| 21 | + @Test |
| 22 | + public void testTransferFrom() { |
| 23 | + try { |
| 24 | + RandomAccessFile fromFile = new RandomAccessFile(fromPath, "rw"); |
| 25 | + FileChannel fromChannel = fromFile.getChannel(); |
| 26 | + |
| 27 | + RandomAccessFile toFile = new RandomAccessFile(toPath, "rw"); |
| 28 | + FileChannel toChannel = toFile.getChannel(); |
| 29 | + |
| 30 | + long position = 0; |
| 31 | + long count = fromChannel.size(); |
| 32 | + |
| 33 | + long transferBytesSize = |
| 34 | + toChannel.transferFrom(fromChannel, position, count); |
| 35 | + Assert.assertEquals(26, transferBytesSize); |
| 36 | + } catch (IOException e) { |
| 37 | + e.printStackTrace(); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void testTransferTo() { |
| 43 | + try { |
| 44 | + RandomAccessFile fromFile = new RandomAccessFile(fromPath, "rw"); |
| 45 | + FileChannel fromChannel = fromFile.getChannel(); |
| 46 | + |
| 47 | + RandomAccessFile toFile = new RandomAccessFile(toPath, "rw"); |
| 48 | + FileChannel toChannel = toFile.getChannel(); |
| 49 | + |
| 50 | + long position = 0; |
| 51 | + long count = fromChannel.size(); |
| 52 | + |
| 53 | + long transferBytesSize = |
| 54 | + fromChannel.transferTo(position, count, toChannel); |
| 55 | + Assert.assertEquals(26, transferBytesSize); |
| 56 | + } catch (IOException e) { |
| 57 | + e.printStackTrace(); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments