这是一种纯javaIO读取文件的方式,相对新版的NIO方式较落后,读取速度也有待提高,但不失为一种经典的文件路径转byte数组的方式,仅供大家学习参考。
package com.util;
import java.io.*;
/**
* 文件读取工具类
*/
public class FileUtil {
/**
* 根据文件路径读取byte[] 数组
*/
public static byte[] readFileByBytes(String filePath) throws IOException {
File file = new File(filePath);
//文件不存在直接抛出异常
if (!file.exists()) {
throw new FileNotFoundException(filePath);
} else {
//文件过大时可能有溢出问题
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
BufferedInputStream in = null;
try {
//文件过大时可能有溢出问题
in = new BufferedInputStream(new FileInputStream(file));
//声明每次读取长度
short bufSize = 1024;
//创建读取长度的容器的byte
byte[] buffer = new byte[bufSize];
//定义标记变量
int len1;
//read方法的参数含义可以自行百度,第二个参数0并非固定,有不通的含义
while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
//循环读取文件
bos.write(buffer, 0, len1);
}
//读取完成的装换成byte数组返回
byte[] var7 = bos.toByteArray();
return var7;
} finally {
try {
//最后关闭流
if (in != null) {
in.close();
}
} catch (IOException var14) {
var14.printStackTrace();
}
bos.close();
}
}
}
}
java中为了方便对文件的操作和快速的读取文件,定义了很多不同文件操作的流。内容较多,非一篇就能讲完,感性趣的可以自行百度。