转自:https://blog.csdn.net/xinxiqi/article/details/78899159
1 package com.sanqing.util; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.IOException; 7 8 /** 9 * 把文件类型转化为byte[] 10 */ 11 public class FileToByte { 12 public static byte[] getBytesFromFile(File f) { 13 if (f == null) { //如果文件为null直接返回一个null 14 return null; 15 } 16 try { 17 FileInputStream stream = new FileInputStream(f);//初始化一个文件输入流 18 ByteArrayOutputStream out = new ByteArrayOutputStream(1000);//初始化一个字节数组输出流 19 byte[] b = new byte[1000];//设置缓存为1000 20 int n; 21 while ((n = stream.read(b)) != -1) 22 //循环读取文件信息 23 out.write(b, 0, n);//写入到字节数组输出流中。 24 stream.close();//关闭输入流 25 out.close();//关闭输出流 26 return out.toByteArray();//返回输出流中的字节数组 27 } catch (IOException e) { 28 } 29 return null; 30 } 31 }