-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathExplicitChannelRead.java
More file actions
50 lines (38 loc) · 1.3 KB
/
Copy pathExplicitChannelRead.java
File metadata and controls
50 lines (38 loc) · 1.3 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
48
49
50
// Use NIO to read a text file.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class ExplicitChannelRead {
public static void main(String args[]) {
FileInputStream fIn;
FileChannel fChan;
long fSize;
ByteBuffer mBuf;
try {
// First, open a file for input.
fIn = new FileInputStream("test.txt");
// Next, obtain a channel to that file.
fChan = fIn.getChannel();
// Now, get the file's size.
fSize = fChan.size();
// Allocate a buffer of the necessary size.
mBuf = ByteBuffer.allocate((int)fSize);
// Read the file into the buffer.
fChan.read(mBuf);
// Rewind the buffer so that it can be read.
// Rewinds this buffer. The position is set to zero and the mark is
// discarded.
mBuf.rewind();
// Read bytes from the buffer.
for(int i=0; i < fSize; i++)
System.out.print((char)mBuf.get());
System.out.println();
// close channel and file
fChan.close();
fIn.close();
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
}
}
}