2015-11-03 12:00:44 -08:00
|
|
|
// newio/GetChannel.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
// Getting channels from streams
|
|
|
|
import java.nio.*;
|
|
|
|
import java.nio.channels.*;
|
|
|
|
import java.io.*;
|
|
|
|
public class GetChannel {
|
|
|
|
private static final int BSIZE = 1024;
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
|
|
// Write a file:
|
|
|
|
FileChannel fc =
|
|
|
|
new FileOutputStream("data.txt").getChannel();
|
|
|
|
fc.write(ByteBuffer.wrap("Some text ".getBytes()));
|
|
|
|
fc.close();
|
|
|
|
// Add to the end of the file:
|
|
|
|
fc =
|
|
|
|
new RandomAccessFile("data.txt", "rw").getChannel();
|
|
|
|
fc.position(fc.size()); // Move to the end
|
|
|
|
fc.write(ByteBuffer.wrap("Some more".getBytes()));
|
|
|
|
fc.close();
|
|
|
|
// Read the file:
|
|
|
|
fc = new FileInputStream("data.txt").getChannel();
|
|
|
|
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
|
|
|
|
fc.read(buff);
|
|
|
|
buff.flip();
|
|
|
|
while(buff.hasRemaining())
|
|
|
|
System.out.write(buff.get());
|
|
|
|
System.out.flush();
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
Some text Some more
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|