在Java 中,如何把二进制文件转化为字节数组(byte[])呢?
看下面的静态方法:
- /**
- * 把二进制文件转化为字节数组
- * @param path :path of specified file
- * @return bytes[]
- * @throws Exception
- */
- public static byte[] toByteArrFromFile(String path) throws Exception{
- File inFile = new File(path);
- FileInputStream fileInputStream = new FileInputStream(inFile);
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- int i;
- //转化为字节数组流
- while ((i = fileInputStream.read()) != -1) {
- byteArrayOutputStream.write(i);
- }
- fileInputStream.close();
- // 把文件存在一个字节数组中
- byte[] bytes = byteArrayOutputStream.toByteArray();
- byteArrayOutputStream.close();
- return bytes;
- }