使用nio自定义文件路径并持久化


@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;
    }

}

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值