import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class GetChannel {
static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
FileChannel channel = new FileOutputStream("data.txt").getChannel();
channel.write(ByteBuffer.wrap("Some text".getBytes()));
channel.close();
channel = new RandomAccessFile("data.txt", "rw").getChannel();
channel.position(channel.size());// 移动到文件结尾
channel.write(ByteBuffer.wrap(" Some more".getBytes()));
channel.close();
channel = new FileInputStream("data.txt").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
channel.read(buffer);
buffer.flip();// 反转此通道
while (buffer.hasRemaining()) {
System.out.println((char) buffer.get());
}
}
}
JAVA 新I/O 之 FileChannel,ByteBuffer
最新推荐文章于 2025-10-16 09:46:53 发布
本文介绍了Java中使用FileChannel进行文件操作的方法,包括写入、读取和位置移动,并展示了如何通过ByteBuffer优化读取效率。
6507

被折叠的 条评论
为什么被折叠?



