1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
通过文件创建channel
RandomAccessFile randomAccessFile = new RandomAccessFile("/Users/peilizhi/file/one.txt", "rw");
final FileChannel channel = randomAccessFile.getChannel();
// 写入的内容
String context = "peilizhi";
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.clear();
// 先放入缓冲区
byteBuffer.put(context.getBytes(StandardCharsets.UTF_8));
// 转换模式,之前是读;现在是写
byteBuffer.flip();
// 如果还有byte
while (byteBuffer.hasRemaining()) {
channel.write(byteBuffer);
}
randomAccessFile.close();
|