文件与二进制数据互转-ByteArrayOutputStream

来源:互联网 发布:linux shell启动jar包 编辑:程序博客网 时间:2024/05/16 05:02
// 获取二进制数据public static byte[] getFileBinary(String filePath) {    FileInputStream fis = null;    BufferedInputStream bis = null;    ByteArrayOutputStream baos = null;    try {        fis = new FileInputStream(filePath);        bis = new BufferedInputStream(fis);        baos = new ByteArrayOutputStream();        int c = bis.read();        while (c != -1) {            // 数据存储到ByteArrayOutputStream中            baos.write(c);            c = bis.read();        }        fis.close();        bis.close();        // 转换成二进制        return baos.toByteArray();    } catch (Exception e) {        e.printStackTrace();    } finally {        // 没有关闭ByteArrayOutputStream流的意义,空实现        try {            if (fis != null ) {                fis.close();            }        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (bis != null ) {                    bis.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }    return null;}// 二进制数据转成文件public static void binaryToFile(byte[] bytes, String filePath) {    FileOutputStream fos = null;    BufferedOutputStream bos = null;    try {        fos = new FileOutputStream(filePath);        bos = new BufferedOutputStream(fos);        bos.write(bytes);    } catch (Exception e) {        e.printStackTrace();    } finally {        try {            if (fos != null ) {                fos.close();            }        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (bos != null ) {                    bos.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }}

ByteArrayOutputStream没有执行close()的意义,原因:底层空实现(源码如下)



0 0
原创粉丝点击