程序员潇然 发表于 2022-7-26 14:42:53

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

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

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

NIO中:

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

其中相关包为:

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

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

```java
    /**
   * 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
   *
   * @returna byte array containing the bytes read from the file
   *
   * @throwsIOException
   *          if an I/O error occurs reading from the stream
   * @throwsOutOfMemoryError
   *          if an array of the required size cannot be allocated, for
   *          example the file is larger that {@code 2GB}
   * @throwsSecurityException
   *          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了,会帮我们处理好异常,我们直接使用结果即可。

!(data/attachment/forum/202206/16/141330jha7st9soow8772i.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/300 "common_log.png")
`转载务必注明出处:程序员潇然,疯狂的字节X,https://crazybytex.com/thread-93-1-1.html `
页: [1]
查看完整版本: [nio] NIO读取文件 优雅的读取本地文件到字节数组