@Slf4j
public final class WriteFileUtil {
/**
* 自定义路径保存
*
* @param resultDetailId 文件唯一标识
* @param filePath 路径
* @param suffix 文件后缀
* @return
*/
public static String getFilePath(String resultDetailId, String filePath,String suffix) {
// 文件保存操作(创建每日文件夹)
String dateFolder = DateUtil.formatDate((new Date()));
filePath = filePath + dateFolder;
File folder = new File(filePath);
if (!folder.exists()) {
folder.mkdirs();
}
// 文件全路径
return filePath + "/" + resultDetailId + "_" + System.currentTimeMillis() + suffix;
}
/**
* 自定义路径保存
*
* @param byteArray 文本字节
* @param filePath 路径
* @return String
*/
public static String writeFile(byte[] byteArray, String filePath) {
try ( //创建一个文件输出流
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
//获取文件输入流的通道
FileChannel channel = fileOutputStream.getChannel()) {
//将要写入到文件中的内容放入缓冲区
ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
//将byteBuffer的内容写入通道
int write = channel.write(byteBuffer);
if (write != byteBuffer.capacity()) {
log.error("文件写入失败:{}", "Error: Failed to write all bytes to FileChannel.");
}
byteBuffer.clear();
} catch (IOException | NullPointerException e) {
log.error("文件写入失败:{}", e.getMessage());
return null;
}
return filePath;
}
}
使用nio自定义文件路径并持久化
最新推荐文章于 2024-07-20 20:32:35 发布