-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleUserOfChannel.java
More file actions
47 lines (35 loc) · 1.13 KB
/
SimpleUserOfChannel.java
File metadata and controls
47 lines (35 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package NIO;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class SimpleUserOfChannel {
public static void main(String[] args){
try {
RandomAccessFile randomFile;
randomFile = new RandomAccessFile("src\\employee.txt", "rw");
FileChannel inChannel= randomFile.getChannel();
ByteBuffer byteBuffer=ByteBuffer.allocate(10);
//从通道中读一组字节序列到缓存中
int bytesRead=inChannel.read(byteBuffer);
while(bytesRead!=-1) {
System.out.println("Read"+bytesRead);
//从buffer中读取数据
byteBuffer.flip();
while(byteBuffer.hasRemaining()) {
System.out.println("buf:"+(char)byteBuffer.get());
}
byteBuffer.clear();
bytesRead=inChannel.read(byteBuffer);
}
randomFile.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}