精通并发与Netyy系列 初步认识NIO文件读写

Java.io中最核心的概念是流(Stream),面向流编程。一个流要么是输入流,要么是出入流,不能是同时是输入流也是出入流。

Java.nio中有三个核心概念:selector、channel、buffer,面向块(block)或者是面向缓冲区(buffer)编程。thread基于事件驱动从而作用在不同的channel上。buffer本身是一块内存, 底层通过数组来实现。数据的读和写都是通过buffer来实现。

 

通过三段示例代码来理解NIO的文件读写

public class Test1 {
    public static void main(String[] args) {
        IntBuffer buffer = IntBuffer.allocate(10);

        for (int i = 0; i < buffer.capacity(); i ++) {
            int randomNumber = new SecureRandom().nextInt(20);
            buffer.put(randomNumber);
        }
        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.println(buffer.get());
        }
    }
}

public class Test2 {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("test.txt");
        FileChannel fileChannel = fileInputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(100);
        fileChannel.read(byteBuffer);

        byteBuffer.flip();
        while (byteBuffer.hasRemaining()) {
            byte c = byteBuffer.get();
            System.out.println((char) c);
        }
        fileChannel.close();
    }
}

public class Test3 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream("test3.txt");
        FileChannel channel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(100);
        byte[] bytes = "hello kitty".getBytes();
        byteBuffer.put(bytes);

        byteBuffer.flip();

        channel.write(byteBuffer);
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值