|
|
|
@ -7,21 +7,33 @@ import java.io.IOException;
|
|
|
|
|
import java.io.InputStream;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 类说明 :
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
* 类说明 : 该类是一个文件处理工具类,提供了将文件转换为字节数组的方法。
|
|
|
|
|
*/
|
|
|
|
|
public class FileUtil {
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 将指定的文件转换为字节数组。
|
|
|
|
|
*
|
|
|
|
|
* @param file 要转换的文件对象
|
|
|
|
|
* @return 包含文件内容的字节数组
|
|
|
|
|
* @throws IOException 如果在读取文件或处理流时发生 I/O 错误
|
|
|
|
|
*/
|
|
|
|
|
public static byte[] FileToByte(File file) throws IOException {
|
|
|
|
|
// 将数据转为流
|
|
|
|
|
// 将文件数据转换为输入流,这里使用 FileInputStream 来读取文件内容
|
|
|
|
|
@SuppressWarnings("resource")
|
|
|
|
|
InputStream content = new FileInputStream(file);
|
|
|
|
|
// 创建一个 ByteArrayOutputStream 用于存储从文件中读取的数据
|
|
|
|
|
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
|
|
|
|
|
// 创建一个字节缓冲区,用于每次从输入流中读取数据
|
|
|
|
|
byte[] buff = new byte[100];
|
|
|
|
|
// 用于存储每次读取的字节数
|
|
|
|
|
int rc = 0;
|
|
|
|
|
// 循环读取文件内容,直到读取完所有数据(read 方法返回 -1 表示读取到文件末尾)
|
|
|
|
|
while ((rc = content.read(buff, 0, 100)) > 0) {
|
|
|
|
|
// 将读取到的字节写入到 ByteArrayOutputStream 中
|
|
|
|
|
swapStream.write(buff, 0, rc);
|
|
|
|
|
}
|
|
|
|
|
// 获得二进制数组
|
|
|
|
|
// 将 ByteArrayOutputStream 中的数据转换为字节数组并返回
|
|
|
|
|
return swapStream.toByteArray();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|