在Java中,若要对IO流或者文件进行处理可使用Hutool工具
https://hutool.cn/docs/#/core/IO/IO工具类-IoUtil
https://hutool.cn/docs/#/core/IO/文件工具类-FileUtil
本文示例代码
package test;
import java.io.*;
public class FileUtil {
/**
* 文件转Byte数组
* @param filePath 文件路径
* @return Byte数组
*/
public static byte[] file2Bytes(String filePath) {
File file = new File(filePath);
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
byte[] data = bos.toByteArray();
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Byte数组转文件
* @param bytes Byte数组
* @param filePath 文件路径
* @param fileName 文件名称
*/
public static void bytes2File(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) { // 判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
评论区