首页 > 其他分享 > 将文件转为byte[]

将文件转为byte[]

时间:2022-12-23 14:14:09浏览次数:40  
标签:文件 fis 转为 bos new byte byteArr

/**
* 将文件转为byte[]
*
* @param filePath 文件路径
* @return
*/
public static byte[] getBytes(String filePath) throws IOException {
File file = new File(filePath);
FileInputStream fis = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
try {
fis = new FileInputStream(file);
//创建个字节数组,给定长度为1000
byte[] byteArr = new byte[1000];
int n;
//进行循环读取文件内容,当read返回值为-1的时候,表示文件读取完毕,就可以显示文件内容
//读取到的字节全部放入到指定的字节数组byteArr 返回每次填充给bytes数组的长度
while ((n = fis.read(byteArr)) != -1) {
//将指定的字节数组写入文件
bos.write(byteArr, 0, n);
}
return bos.toByteArray();
} catch (Exception e) {
log.error("将文件转换成Byte数组失败", e);
} finally {
if (fis != null) {
fis.close();
}
bos.close();
}
return null;
}

标签:文件,fis,转为,bos,new,byte,byteArr
From: https://www.cnblogs.com/fightmonster/p/17000542.html

相关文章