Channel和Buffer示例File file = new RandomAccessFile("data.txt", "rw");FileChannel channel = file.getChannel();ByteBuffer buffer = ByteBuffer.allocate(48);int bytesRead = channel.read(buffer);while (bytesRead != -1) { System.out.println("Read " + bytesRead); buffer.flip(); while(buffer.hasRemaining()){ System.out.print((char) buffer.get()); } buffer.clear(); bytesRead = channel.read(buffer);}file.close();注意buffer.flip() 的调用,首先将数据写入到buffer,然后变成读模式,再从buffer中读取数据。
总结通过本文的介绍,希望大家对Channel和Buffer在文件读写方面的应用和内部实现有了一定了解,努力做到不被一叶障目。 |