本文主要记录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了,会帮我们处理好异常,我们直接使用结果即可。
转载务必注明出处:程序员潇然,疯狂的字节X,https://crazybytex.com/thread-93-1-1.html |