工具类如下
import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileUtil { private static Logger logger = LoggerFactory.getLogger(FileUtil.class); //byte to file public static void byte2File(byte[] bfile, String filePath, String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); if (!dir.exists()) {// 判断文件目录是否存在 dir.mkdirs(); } file = new File(filePath + fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bfile); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (bos != null) { try { bos.close(); } catch (IOException e1) { logger.error(e1.getMessage(), e1); } } if (fos != null) { try { fos.close(); } catch (IOException e1) { logger.error(e1.getMessage(), e1); } } } } //file to byte public static byte[] file2Byte(File filePath) { byte[] buffer = null; try { FileInputStream fis = new FileInputStream(filePath); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); } catch (IOException e) { logger.error("error message {}", e.getMessage()); } return buffer; } }