Java Reference
In-Depth Information
// Wrap the text into a char buffer
CharBuffer charBuffer = CharBuffer.wrap(sb);
// Encode the char buffer data into a byte buffer
ByteBuffer byteBuffer = cs.encode(charBuffer);
// Write the data to the file
seekableChannel.write(byteBuffer);
}
public static void readData(SeekableByteChannel seekableChannel,
Charset cs) throws IOException {
ByteBuffer byteBuffer = ByteBuffer.allocate(128);
String encoding = System.getProperty("file.encoding");
while (seekableChannel.read(byteBuffer) > 0) {
byteBuffer.rewind();
CharBuffer charBuffer = cs.decode(byteBuffer);
System.out.print(charBuffer);
byteBuffer.flip();
}
}
public static void printDetails(SeekableByteChannel seekableChannel, String msg) {
try {
System.out.println(msg + ": Size = " +
seekableChannel.size() +
", Position = " + seekableChannel.position());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Before writing data: Size = 0, Position = 0
After writing data: Size = 128, Position = 128
After resetting position to 0: Size = 128, Position = 0
When the blazing sun is gone,
When he nothing shines upon,
Then you show your little light,
Twinkle, twinkle, all the night
After reading data: Size = 128, Position = 128
Traversing a File Tree
NIO.2 provides a FileVisitor API to recursively process all files and directories in a file tree. The FileVisitor API is useful
when you want to perform some actions on all or some files or directories in a file tree. For example, you cannot delete
a directory until it is empty. Before you delete a directory, you must delete all files and directories underneath it,
which can be achieved easily using the FileVisitor API.
 
Search WWH ::




Custom Search