Channel & ByteBuffer channal & buffer - ByteBuffer
package think.in.java.io;
/**
* That are closer to the operating system’s way of performing I/O: channels and buffers.
* The only kind of buffer that communicates directly with a channel is a ByteBuffer—that is,
* a buffer that holds raw bytes.
*
* It’s fairly low-level, precisely because this makes a more efficient mapping with most operating systems.
*
* Here’s a simple example that exercises all three types of stream
* to produce channels that are writeable, read/writeable, and readable:
* @author WPeng
*
* @since 2012-11-6
*/
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);
/**
Reads a sequence of bytes from this channel into the given buffer.
Bytes are read starting at this channel's current file position,
and then the file position is updated with the number of bytes actually read.
-1 if the channel has reached end-of-stream
*/
fc.read(buff);
buff.flip();
while(buff.hasRemaining()){
System.out.print((char)buff.get());
}
}
}
transferTo & transferFrompackage think.in.java.io;
/**
* Using transferTo() between channels
* {Args: TransferTo.java TransferTo.txt}
* @author WPeng
*
* @since 2012-11-6
*/
public class TransferTo {
public static void main(String[] args) throws IOException{
if(args.length != 2){
System.out.println("arguments: sourcefile destfile");
System.exit(1);
}
FileChannel in = new FileInputStream(args[0]).getChannel(),
out = new FileOutputStream(args[1]).getChannel();
in.transferTo(0, in.size(), out);
// or:
// out.transferFrom(in, 0, in.size());
}
}