码迷,mamicode.com
首页 > 其他好文 > 详细

关于流的转换

时间:2019-09-24 17:51:23      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:write   put   new   upload   length   final   service   not   routes   

  /**
     * file文件转byte数组
     * */
public byte[] fileToByte(String filePath){ byte[] data = null; FileInputStream fis = null; ByteArrayOutputStream baos = null; try { fis = new FileInputStream(filePath); baos = new ByteArrayOutputStream(); int len; byte[] buffer = new byte[1024]; while ((len = fis.read(buffer)) != -1) { baos.write(buffer, 0, len); } data = baos.toByteArray(); fis.close(); baos.close(); } catch (Exception e) { log.error("FileUpload_fileToByte_error:"+e.toString()); } return data; }
   /**
     * file文件压缩后转成base64
     * */
    public static String zipByteArrayOutputStream(String filePath) {
        File zip = ZipUtil.zip(filePath);
        if (null == zip){
            throw new BizException(ErrCode.UserEnum.FILE_NOT_EXIST);
        }
        String result = null;
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(zip);
            byte[] bytes = new byte[(int)zip.length()];
            inputFile.read(bytes);
            result= Base64.getEncoder().encodeToString(bytes);
        }catch (Exception e){
            log.error("YLVirtualAccountRouteServiceImpl_FileUpload 文件压缩转Base64失败:"+e.toString());
            throw new BizException(ErrCode.UserEnum.ZIP_TO_FILE_ERROR);
        }finally {
            try {
                inputFile.close();
            }catch (Exception e){
                log.error("YLVirtualAccountRouteServiceImpl_FileUpload 文件压缩转Base64失败:"+e.toString());
                throw new BizException(ErrCode.UserEnum.ZIP_TO_FILE_ERROR);
            }
        }
        return result;
    }
/** * base64 转成file * */
public
static void base64ToFile(String base64,String targetPath,String fileName)throws Exception { byte[] decode = Base64.getDecoder().decode(base64); FileOutputStream out = new FileOutputStream(targetPath+"/"+fileName); out.write(decode); out.close(); }

 

关于流的转换

标签:write   put   new   upload   length   final   service   not   routes   

原文地址:https://www.cnblogs.com/bokai/p/11579303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!