將File或者InputStream轉成byte陣列
阿新 • • 發佈:2018-11-14
package com.yinhai.demo.utils; import java.io.*; /** * 將File或者InputStream轉成byte陣列 * * Created by Blossom on 2018/7/28. */ public class FileUtil { public static byte[] File2byte(String filePath) throws Exception { 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 byte[] inputStreamToByte(InputStream is) throws Exception{ BufferedInputStream bis = new BufferedInputStream(is); byte [] a = new byte[1000]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = bis.read(a))!=-1){ bos.write(a, 0, len); } bis.close(); bos.close(); return bos.toByteArray(); } }