You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hotels/back/src/main/java/com/utils/FileUtil.java

39 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
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();
}
}