数据通讯通道(Channel) 之FileChannel用法简单示例

1、使用FileChannel 从文件中读取数据

channel是一个通道,通过它可以写入或者读取数据。所有的数据都得通过buffer来处理,

使用NIO来读取数据,一般使用FileChannel的步骤为:

  • 1、从FileInputStream中获取到Channel
  • 2、创建一个用来存放数据的容器(buffer)
  • 3、将数据从channel中读入到buffer中。
    /**
     * 测试使用FileChannel来读取文件
     */
    @Test
    public void testFileChannel() throws IOException {
        FileInputStream is = new FileInputStream("abc.txt");
        FileChannel channel = is.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        channel.read(buffer);
        buffer.flip();

        System.out.println(new String(read(buffer)));
    }
    /**
     * 从buffer将数据读取到数组中
     * @param buffer
     * @return
     */
    public static  byte[] read(ByteBuffer buffer){
        byte[] bytes = new byte[buffer.limit() - buffer.position()];
        buffer.get(bytes);
        return  bytes;
    }

2、使用FileChannel 向文件中写入数据

使用NIO写入数据的步骤一般如下:

  • 1、从FileOutputStream 获取数据
  • 2、创建buffer
  • 3、将数据从channel写入buffer
    /**
     * 测试使用FileChannel来写入文件
     * @throws IOException
     */
    @Test
    public void TestFileChannelWrite() throws IOException {
        FileOutputStream os = new FileOutputStream("abc.txt");
        FileChannel channel = os.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(26);

        //向buffer 中写入26个英文字母
        for(byte i= 65;i<65+26;i++){
            buffer.put(i);
        }
        buffer.flip();
        channel.write(buffer);
        channel.close();


    }

写入成功后,我们打开项目根目录下的abc.txt文件查看里

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值