将文件转为byte[]

/**
 * 将文件转为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;
}
posted @ 2022-12-23 13:57  码农公子的幸福生活  阅读(882)  评论(0)    收藏  举报