Skip to content

Commit f5dc036

Browse files
committed
[add] add ChannelTransferTest for NIO
1 parent 6a4b02c commit f5dc036

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
1234567
2+
qwertyusfdf
3+
asdsad

0 commit comments

Comments
 (0)