-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGetChannel.java
More file actions
42 lines (35 loc) · 1.09 KB
/
GetChannel.java
File metadata and controls
42 lines (35 loc) · 1.09 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
package io;
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
import java.util.*;
/**
* RUN:
* javac io/GetChannel.java && java io.GetChannel
*
* OUTPUT:
*
*/
public class GetChannel {
private static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
// write in file
FileChannel fc = new FileOutputStream("io/data.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text ".getBytes()));
fc.close();
// append to end of file
fc = new RandomAccessFile("io/data.txt", "rw").getChannel();
fc.position(fc.size()); // move to end of file
fc.write(ByteBuffer.wrap("Some more ".getBytes()));
fc.close();
// read from file
fc = new FileInputStream("io/data.txt").getChannel();
// ByteBuffer buff = ByteBuffer.allocateDirect(BSIZE);
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
fc.read(buff);
buff.flip();
while (buff.hasRemaining()) {
System.out.print((char)buff.get());
}
}
}