File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed
java/com/brianway/learning/java/nio/tutorial Expand file tree Collapse file tree 2 files changed +45
-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
+ * 基本的 Channel 示例
10
+ * 一个使用FileChannel读取数据到Buffer中的示例
11
+ *
12
+ * @auther brian
13
+ * @since 2019/6/17 23:41
14
+ */
15
+ public class ChannelDemo {
16
+ public static void main (String [] args ) {
17
+ try {
18
+ String path = ChannelDemo .class .getResource ("/" ).getPath () + "channel-demo.txt" ;
19
+ RandomAccessFile aFile = new RandomAccessFile (path , "rw" );
20
+ FileChannel inChannel = aFile .getChannel ();
21
+ // 该值小于文件内容的长度时,结果不同
22
+ int bufferSize = 48 ;
23
+ ByteBuffer buf = ByteBuffer .allocate (bufferSize );
24
+
25
+ int bytesRead = inChannel .read (buf );
26
+ while (bytesRead != -1 ) {
27
+
28
+ System .out .println ("Read " + bytesRead );
29
+ buf .flip ();
30
+
31
+ while (buf .hasRemaining ()) {
32
+ System .out .print ((char ) buf .get ());
33
+ }
34
+
35
+ buf .clear ();
36
+ bytesRead = inChannel .read (buf );
37
+ }
38
+ aFile .close ();
39
+ } catch (IOException e ) {
40
+ e .printStackTrace ();
41
+ }
42
+ }
43
+ }
Original file line number Diff line number Diff line change
1
+ 0123456789
2
+ asdf
You can’t perform that action at this time.
0 commit comments