File和byte[]转换
Posted donaldlee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了File和byte[]转换相关的知识,希望对你有一定的参考价值。
http://blog.csdn.net/commonslok/article/details/9493531
public static byte[] File2byte(String filePath) { byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); 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 (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } public static void byte2File(byte[] buf, String filePath, String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); if (!dir.exists() && dir.isDirectory()) { dir.mkdirs(); } file = new File(filePath + File.separator + fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
以上是关于File和byte[]转换的主要内容,如果未能解决你的问题,请参考以下文章
将 HttpPostedFileBase 转换为 byte[]
java 中 byte[]FileInputStream 互相转换
java 中 byte[]FileInputStream 互相转换