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();
            }
        }
    }
}