前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >open()+直接缓冲区使用原理

open()+直接缓冲区使用原理

原创
作者头像
用户7108768
修改2021-09-26 17:48:00
修改2021-09-26 17:48:00
41700
代码可运行
举报
运行总次数:0
代码可运行

通过非直接缓冲区读写数据,需要通过通道来传输缓冲区里的数据

代码语言:javascript
代码运行次数:0
复制
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class demo4 {
    public static void main(String[] args) {
        FileInputStream is = null;
        FileOutputStream os = null;
        // 获得通道
        FileChannel inChannel = null;
        FileChannel outChannel = null;

        // 利用 try-catch-finally 保证关闭
        try {
            is = new FileInputStream("");
            os = new FileOutputStream("");

            // 获得通道
            inChannel = is.getChannel();
            outChannel = os.getChannel();

            // 获得缓冲区,用于在通道中传输数据
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            // 循环将字节数据放入到buffer中,然后写入磁盘中
            while (inChannel.read(byteBuffer) != -1) {
                // 切换模式
                byteBuffer.flip();
                outChannel.write(byteBuffer);
                byteBuffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inChannel != null) {
                try {
                    inChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outChannel != null) {
                try {
                    outChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
open()+直接缓冲区
  • 通过open获得通道
  • 通过FileChannel.map()获取直接缓冲区

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • open()+直接缓冲区
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档