【Java】Files.readAllBytes(Path) 遇见的坑

Files.readAllBytes(Path)方法把整个文件读入内存,此方法返回一个字节数组,还可以把结果传递给String的构造器,以便创建字符串输出。

在针对大文件的读取的时候,可能会出现内存不足,导致堆溢出。

最后还是采用原始的IO方式去读写文件,将文件读入byt数组中

InputStream input = null;
byte[] byt = null;
try {
File file = localPath.toFile();
input = new FileInputStream(file);

byt = new byte[input.available()];

input.read(byt);
} catch (FileNotFoundException e) {
logger.info("file not find!");
} catch (IOException e) {
logger.info("IOException :" + e);
}finally {
input.close();
}
原文地址:https://www.cnblogs.com/whutwxj/p/8289065.html