Skip to content

Commit 323a55e

Browse files
committed
[add] add Channel demo
1 parent 944dcf6 commit 323a55e

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
0123456789
2+
asdf

0 commit comments

Comments
 (0)