IO记录

作者: 2efa470dd3ae | 来源:发表于2019-03-12 14:23 被阅读0次
    /**
     * 文件转换成字节数组
     * @param filePath
     * @return
     */
    public static byte[] fileToByteArray(String filePath) {
        File file = new File(filePath);
        byte[] dest = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            is = new FileInputStream(file);
            byte[] flush = new byte[1024];
            int len = -1;
            while ((len = is.read(flush)) != -1) {
                baos.write(flush, 0, len);

            }
            baos.flush();
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 字节数组转换成文件
     * @param filePath
     * @return
     */
    public static void byteArrayToFile(byte[] src, String filePath) {
        File dest = new File(filePath);
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new ByteArrayInputStream(src);
            os = new FileOutputStream(dest);
            byte[] flush = new byte[5];
            int len = -1;
            while ((len = is.read(flush)) != -1) {
                os.write(flush, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

相关文章

网友评论

      本文标题:IO记录

      本文链接:https://www.haomeiwen.com/subject/jpzgpqtx.html