java 中如何把文件(file)转化字节数组呢?
方式一:
/**
* 文件转换为二进制数组
*
* @param file 文件对象
* @return
* @throws IOException
*/
public static byte[] fileTobytes(final File file) throws IOException {
byte[] data = null;
if (file.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
int length = fileInputStream.available();
data = new byte[length];
fileInputStream.read(data);
fileInputStream.close();
}
return data;
}
方式二:
/***
* read file ,convert file to byte array
*
* @param file
* @return
* @throws IOException
*/
public static byte[] readBytes4file(File file) throws IOException{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
// System.out.println("Available bytes:" + in.available());
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
in.close();
byte[] content = out.toByteArray();
return content;
}