JAVA将文件转换成byte数组(byte[])

时间:2023-03-09 04:28:55
JAVA将文件转换成byte数组(byte[])
 /**
* 将文件转换成byte数组
* @param filePath 文件File类 通过new File(文件路径)
* @return byte数组
*/
public static byte[] File2byte(File filePath) {
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(filePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}