用 BIO NIO AIO 实现文件读写练习

本文通过示例代码详细介绍了Java中的三种IO操作模式:传统同步阻塞IO(BIO)、同步非阻塞IO(NIO)及异步非阻塞IO(AIO),并提供了具体的文件读写实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 BIO: 传统的同步阻塞IO   NIO: 同步非阻塞IO   AIO:异步非阻塞IO

 类比烧水:bio一直看着烧开   nio每过一会看一下烧开没有  aio:烧开了烧水壶会响

public class IOReadFile {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        readFileByIO();
    }

    public static void readFileByIO() throws IOException, ClassNotFoundException {
        User user = new User("小松", 20);
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\tempFile.txt"));
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\tempFile.txt"));) {
            oos.writeObject(user.toString().getBytes("UTF-8"));
            System.out.println(user.toString());
            System.out.println(Charset.defaultCharset().displayName());
            System.out.println(ois.readObject());
        }
    }
}
public class NIOReadFile {
    public static void main(String[] args) throws IOException {
        nioReadFile();
        nioWriteFile();
    }

    public static void nioReadFile() throws IOException {
        String path = "D:\\tempFile.txt";
        try (FileInputStream fileInputStream = new FileInputStream(new File(path)); FileChannel channel = fileInputStream.getChannel();) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(100);

            int len = -1;
            while ((len = channel.read(byteBuffer)) != 0    ) {
                byteBuffer.clear();
                byte[] array = byteBuffer.array();
                System.out.write(array, 0, array.length);
                System.out.println("读取长度:"+len);
            }
        }
    }

    public static void nioWriteFile() throws IOException {
        String path = "D:\\out.txt";
        FileOutputStream fileOutputStream = new FileOutputStream(path);
        FileChannel channel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = Charset.forName("UTF-8").encode("使用nio存储到文件");
        int len = 0;
        while ((len = channel.write(byteBuffer)) != 0) {
            System.out.println("写入长度:" + len);
        }
    }
}

 

public class AIOReadFile {
    public static void main(String[] args) throws IOException {
        // aioReadFile();
        // aioWriteFile();
        aioWriteFile_2();
    }

    public static void aioReadFile() throws IOException {
        Path path = Paths.get("D:\\out.txt");
        try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            Future<Integer> read = fileChannel.read(byteBuffer, 0);
            while (!read.isDone()) {
                System.out.println("reading");
            }
            System.out.println(read.isDone());
            System.out.println(byteBuffer);
            byte[] array = byteBuffer.array();
            System.out.println(array.length);

            System.out.println(new String(array, "UTF-8"));
        }
    }

    public static void aioWriteFile() throws IOException {
        Path path = Paths.get("D:\\outaio.txt");
        try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE);) {
            ByteBuffer byteBuffer = ByteBuffer.wrap("我就想写点东西".getBytes("UTF-8"));
            /**
             * 设置capacity position limit 在读写模式下 capacity相同 都是设置的缓冲区大小 limit读是缓存中实际数据多少 写模式下=capacity
             * 因此此处就position重要 表示设置bytebuffer从头开始写
             * 
             * byteBuffer.flip();
             */
            Future<Integer> write = fileChannel.write(byteBuffer, 0);
            while (!write.isDone()) {
                System.out.println("writing");
            }
            System.out.println(write.isDone());
            System.out.println(new String(byteBuffer.array(), "UTf-8"));
        }
    }

    public static void aioWriteFile_2() throws IOException {
        Path path = Paths.get("D:\\outaio2.txt");
        try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE);) {
            ByteBuffer byteBuffer = ByteBuffer.wrap("我就想写点东西".getBytes("UTF-8"));
            /**
             * 设置capacity position limit 在读写模式下 capacity相同 都是设置的缓冲区大小 limit读是缓存中实际数据多少 写模式下=capacity
             * 因此此处就position重要 表示设置bytebuffer从头开始写
             *
             * byteBuffer.flip();
             */
            fileChannel.write(byteBuffer, 0, "anything is ok here", new CompletionHandler<Integer, String>() {
                @Override
                public void completed(Integer result, String attachment) {
                    System.out.println(result + "/" + attachment);
                    System.out.println(byteBuffer);
                }

                @Override
                public void failed(Throwable exc, String attachment) {
                    System.out.println(byteBuffer);
                }
            });
            //这里没法获取write对象 所以不能像上面一样判断是否结束 所以让线程睡一会
            Thread.sleep(5050);
            System.out.println(new String(byteBuffer.array(), "UTf-8"));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值