每日一词——IO + NIO + NIO2

本文探讨了IO、NIO和NIO2在处理文件操作上的区别和进化。IO以字节或字符为单位,NIO引入缓存以提高效率,而NIO2通过抽象接口简化了文件系统交互,提供了Path、DirectoryStream和FileSystem等类以方便操作。示例代码展示了从简单的文件复制到读写属性的进阶操作。

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

大家都干了什么事情

IO

以字节、字符为单位进行低逼格的处理:通过InputStream || Reader 连接 source,通过 OutoutStream || Writer 连接 destination

NIO

以 缓存 为单位进行高逼格的处理:通过 Chanel 连接 source 及 destination

NIO2

对文件系统进行了封装,开发者只需要使用抽象的接口,其内部实现交给各个文件系统的厂商来实现,所以 java 的包分两类,一类供开发者使用:java.nio.file, java.nio.file.attribute,一类供厂商使用:java.nio.file.spi

3段代码演示其核心思想(其实也可以看出来他们的确是越来越看起来简单)

IO核心代码

    public static void save(Reader src, Writer dest) {
        try(Reader input = src;Writer output = dest) {
            int length = -1;
            char[] data = new char[1024];
            while ((length = input.read(data)) != -1) 
                output.write(data, 0, length);
        } catch (IOException e) {
            logger.info("错误信息:{}", e.getMessage());
        }
    }

NIO核心代码块

    public void dump(ReadableByteChannel src, WritableByteChannel dest) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try(ReadableByteChannel srcCH = src; WritableByteChannel destCH = dest) {
            buffer.flip();  // position = 0; limit = buffer当前元素数量
            destCH.write(buffer);
            buffer.clear(); // postion = 0; limit = buffer容量
        } catch (IOException e) {
            logger.info(e.getMessage());
        }
    }

不难看出,IO相比较NIO,多了一个 int length, 记录每次有多少元素被读到


这里写图片描述

NIO2 核心代码
1、操作路径:Path path = Path.get(System.getProperty(“user.home”, “Document”, “Downloads”);
2、属性读取:BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
3、属性赋值:Files.setAttribute(Paths.get(“C:\workspace\Main.java”, “basic:lastModifiedTime”, FileTime.fromMillis(System.currentTimeMillis()));
4、操作文档:
1)Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING
2)BufferedReader reader = Files.newBufferedReader(filePath, “UTF-8”);
instead of
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file, “UTF-8”)));

Path: An object that may be used to locate a file in a file system.


DirectoryStream: A directory stream allows for the convenient use of the for-each construct to iterate over adirectory.


FileSystem: This class defines the {@link #getDefault getDefault} method to get the default file system and factory methods to construct other types of file systems.


Files: This class consists exclusively of static methods that operate on files, directories, or other types of files.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值