byte[]和File相互转换
1.File转byte[]
/** * 文件转byte数组 * @param file * @return * @throws IOException */ public static byte[] fileToByte(File file) throws IOException{ FileInputStream in = new FileInputStream(file); BufferedInputStream bf = new BufferedInputStream(in); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] bytes = new byte[2048000]; int len = 0; while((len=in.read(bytes)) != -1){ bout.write(bytes,0,len); } byte[] fileBytes = bout.toByteArray(); return fileBytes; }
2.byte[]转File
/** * byte数组转文件 * @param bytes * @return * @throws IOException */ public static File byteToFile(byte[] bytes,String path,String name) throws IOException{ File dir = new File(path); if(!dir.exists()&&!dir.isDirectory()){//判断文件目录是否存在 dir.mkdirs(); } File file = new File(path + "\\" + name); FileOutputStream fout = new FileOutputStream(file); BufferedOutputStream bout = new BufferedOutputStream(fout); bout.write(bytes); return file; }