2-nio使用Buffer和channel实现写数据到文件中

package com.netty.bufferandchannel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Fighting
 * @version BufferAndChannel, v 0.1 2020/8/11 23:27 Fighting
 * @Content 使用nio实现向文件中写入字符串
 *
 * --------------------------------------------
 * --------------JDK io FileOutPutStream
 * ---------------^^^
 * ---------------||FileChannel [FileChannelImpl]
 * ---------------^^^^^^
 * ----------------Buffer [Bytebuffer]
 * ----------------^^^数据^^^
 */
public class BufferAndChannelWrite {
    public static void main(String[] args) throws IOException {
        String str = "hello,Fighting中文";//一个中文用UTF-8编码转为字节时占用3个字节

        FileOutputStream fileOutputStream = new FileOutputStream("G:\\netty-workspace\\netty-test\\src\\main\\java\\com\\netty\\bufferandchannel\\demo.txt");

        //通过原生io Api获取nio中的channel
        FileChannel channel = fileOutputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //将字符串放入buffer
        buffer.put(str.getBytes());

        //由写入改为读取
        //position limit
        //position limit 的变化
        buffer.flip();

        //buffer中的数据写入到channel
        // public int write(ByteBuffer var1)//将缓冲区的数据写入到通道中
        channel.write(buffer);

        fileOutputStream.close();
    }
}
public abstract class Buffer {
    private int mark = -1;
    private int position = 0;
    private int limit;
    private int capacity;
}

在调用的时候需要特别看一下Buffer类中这几个参数的变化!

理解:

channel.write(buffer);//此处还需要补充,限于水平没能理解此处将缓冲区的数据写入通道后调用底层的IOUtils.write(Buffer bf),便完成了输出数据...
FileOutputStream

public class FileOutputStream extends OutputStream
{
    /**
     * The system dependent file descriptor.
     */
    private final FileDescriptor fd;

    /**
     * True if the file is opened for append.
     */
    private final boolean append;

    /**
     * The associated channel, initialized lazily.
     */
    private FileChannel channel;
}

 

可见原始io.FileOutputStream中包含了channel的对应操作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值