关于流的转换

  /**
     * 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(); }

 

posted @ 2019-09-24 16:57  love_xiaosha  阅读(172)  评论(0编辑  收藏  举报