Java如何将数据从缓冲区读入通道?
在此示例中,您将看到如何使用FileChannel.write()方法调用从缓冲区读取数据。从缓冲区读取意味着您正在将数据写入通道对象。在下面的代码段中,来自虚拟缓冲区的数据将被读取并写入result.txt文件。
package org.nhooo.example.io;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class BufferRead {
public static void main(String[] args) throws Exception {
FileChannel channel = null;
try {
//定义输出文件并创建FileOutputStream的实例
File file = new File("result.txt");
FileOutputStream fos = new FileOutputStream(file);
//创建一个虚拟ByteBuffer,该值将被读取到通道中。
ByteBuffer buffer = ByteBuffer.allocate(256);
buffer.put(new byte[] {65, 66, 67, 68, 69, 70, 71, 72, 73, 74});
//将缓冲区从写入模式更改为读取模式。
buffer.flip();
//从FileOutputStream对象获取频道并读取
//使用channel.write()方法在缓冲区中可用的数据。
channel = fos.getChannel();
int bytesWritten = channel.write(buffer);
System.out.println("written : " + bytesWritten);
} finally {
if (channel != null && channel.isOpen()) {
channel.close();
}
}
}
}
热门推荐
10 生日奶茶红包祝福语简短
11 生气蛋糕祝福语大全简短
12 幼师离别祝福语老师简短
13 媒人婚礼祝福语简短大气
14 闺蜜小孩祝福语简短
15 新年简短祝福语给亲人
16 端午送老师祝福语简短
17 妈妈病人出院祝福语简短
18 简短的祝福语中秋搞笑