关于流的转换
Posted bokai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于流的转换相关的知识,希望对你有一定的参考价值。
/** * 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(); }
以上是关于关于流的转换的主要内容,如果未能解决你的问题,请参考以下文章