File tree Expand file tree Collapse file tree 2 files changed +62
-0
lines changed
java/com/brianway/learning/java/nio/tutorial Expand file tree Collapse file tree 2 files changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .brianway .learning .java .nio .tutorial ;
2
+
3
+ import java .io .IOException ;
4
+ import java .io .RandomAccessFile ;
5
+ import java .nio .ByteBuffer ;
6
+ import java .nio .channels .FileChannel ;
7
+
8
+ /**
9
+ * 使用Buffer的例子
10
+ *
11
+ * @auther brian
12
+ * @since 2019/6/18 00:26
13
+ */
14
+ public class BufferDemo {
15
+ public static void main (String [] args ) throws IOException {
16
+ String path = BufferDemo .class .getResource ("/" ).getPath () + "buffer-demo.txt" ;
17
+ RandomAccessFile aFile = new RandomAccessFile (path , "rw" );
18
+ FileChannel inChannel = aFile .getChannel ();
19
+
20
+ //create buffer with capacity of 48 bytes
21
+ ByteBuffer buf = ByteBuffer .allocate (48 );
22
+
23
+ //read into buffer.
24
+ int bytesRead = inChannel .read (buf );
25
+ while (bytesRead != -1 ) {
26
+
27
+ //make buffer ready for read
28
+ buf .flip ();
29
+
30
+ while (buf .hasRemaining ()) {
31
+ // read 1 byte at a time
32
+ System .out .print ((char ) buf .get ());
33
+ }
34
+
35
+ //make buffer ready for writing
36
+ // System.out.println("------");
37
+ buf .clear ();
38
+ bytesRead = inChannel .read (buf );
39
+ }
40
+ aFile .close ();
41
+ }
42
+ }
Original file line number Diff line number Diff line change
1
+ 0123456789
2
+ asdf
3
+ 123456789
4
+ asdf
5
+ 23456789
6
+ asdf
7
+ 3456789
8
+ asdf
9
+ 456789
10
+ asdf
11
+ 0123456789
12
+ asdf
13
+ 123456789
14
+ asdf
15
+ 23456789
16
+ asdf
17
+ 3456789
18
+ asdf
19
+ 456789
20
+ asdf
You can’t perform that action at this time.
0 commit comments