[代码段] [nio] NIO读取文件 优雅的读取本地文件到字节数组

技术实战 技术实战 7253 人阅读 | 0 人回复

本文主要记录NIO文件的读取,如何把文件读取到内存,转换成字节数组。

Java的早期IO大家想必已经使用了很多年,虽然模式化用起来并不复杂,但是超级啰嗦。

NIO中:

        Path path = Paths.get("C:\\Users\\crazybytex\\Desktop\\潇然.jpg");
        byte[] contents = Files.readAllBytes(path);

其中相关包为:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

看下相关方法,path简单说就是中文的路径一词抽象,看下readAllBytes方法:

    /**
     * Reads all the bytes from a file. The method ensures that the file is
     * closed when all bytes have been read or an I/O error, or other runtime
     * exception, is thrown.
     *
     * <p> Note that this method is intended for simple cases where it is
     * convenient to read all bytes into a byte array. It is not intended for
     * reading in large files.
     *
     * @param   path
     *          the path to the file
     *
     * @return  a byte array containing the bytes read from the file
     *
     * @throws  IOException
     *          if an I/O error occurs reading from the stream
     * @throws  OutOfMemoryError
     *          if an array of the required size cannot be allocated, for
     *          example the file is larger that {@code 2GB}
     * @throws  SecurityException
     *          In the case of the default provider, and a security manager is
     *          installed, the {@link SecurityManager#checkRead(String) checkRead}
     *          method is invoked to check read access to the file.
     */
    public static byte[] readAllBytes(Path path) throws IOException {
        try (SeekableByteChannel sbc = Files.newByteChannel(path);
             InputStream in = Channels.newInputStream(sbc)) {
            long size = sbc.size();
            if (size > (long)MAX_BUFFER_SIZE)
                throw new OutOfMemoryError("Required array size too large");

            return read(in, (int)size);
        }
    }

第一句简单翻译就是:

读取文件中的所有字节。

该方法确保在读取所有字节或引发I/O错误或其他运行时异常时关闭文件。

看到这就OK了,会帮我们处理好异常,我们直接使用结果即可。

common_log.png 转载务必注明出处:程序员潇然,疯狂的字节X,https://crazybytex.com/thread-93-1-1.html

关注下面的标签,发现更多相似文章
    黄小斜学Java

    疯狂的字节X

  • 目前专注于分享Java领域干货,公众号同步更新。原创以及收集整理,把最好的留下。
    包括但不限于JVM、计算机科学、算法、数据库、分布式、Spring全家桶、微服务、高并发、Docker容器、ELK、大数据等相关知识,一起进步,一起成长。
热门推荐
海康摄像头接入 wvp-GB28181-pro平台测试验
[md]### 简介 开箱即用的28181协议视频平台 `https://github.c
[CXX1300] CMake '3.18.1' was not
[md][CXX1300] CMake '3.18.1' was not found in SDK, PATH, or
[若依]微服务springcloud版新建增添加一个
[md]若依框架是一个比较出名的后台管理系统,有多个不同版本。