Skip to content

Commit 6a4b02c

Browse files
committed
[add] add GatherTest for nio
1 parent 2c8cdc8 commit 6a4b02c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.brianway.java.nio.tutorial;
2+
3+
import com.brianway.learning.java.nio.tutorial.BufferDemo;
4+
import org.junit.Test;
5+
6+
import java.io.IOException;
7+
import java.io.RandomAccessFile;
8+
import java.nio.ByteBuffer;
9+
import java.nio.channels.FileChannel;
10+
import java.nio.charset.Charset;
11+
12+
/**
13+
* @auther brian
14+
* @since 2019/6/18 23:51
15+
*/
16+
public class GatherTest {
17+
18+
private String path = BufferDemo.class.getResource("/").getPath() + "gather.txt";
19+
20+
@Test
21+
public void testGatheringWrites() throws IOException {
22+
RandomAccessFile aFile = new RandomAccessFile(path, "rw");
23+
FileChannel channel = aFile.getChannel();
24+
ByteBuffer header = ByteBuffer.allocate(128);
25+
ByteBuffer body = ByteBuffer.allocate(1024);
26+
27+
header.put("这是头".getBytes(Charset.forName("UTF-8")));
28+
body.put("this is body.".getBytes(Charset.forName("UTF-8")));
29+
header.flip();
30+
body.flip();
31+
//write data into buffers
32+
ByteBuffer[] bufferArray = {header, body};
33+
// 注意只有position和limit之间的数据才会被写入
34+
channel.write(bufferArray);
35+
channel.close();
36+
}
37+
}

0 commit comments

Comments
 (0)