File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
java-io/src/test/java/com/brianway/java/nio/tutorial Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments