You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LocalDateTime拼接文件名异常:后缀-encryptedText.txt丢失求助

问题排查与解决方案

问题原因

直接拼接LocalDateTime对象时,它的默认toString()方法会生成带冒号(:)的字符串(例如2024-05-20T14:30:00)。而Windows系统的文件名不允许包含冒号,系统处理这类文件名时会自动截断冒号后的内容,导致后缀-encryptedText.txt被丢弃,最终只剩LocalDateTime的部分。

修复步骤

  1. 使用DateTimeFormatter将LocalDateTime格式化为不含文件名非法字符的字符串,比如选择无冒号的格式(如yyyyMMddHHmmss或yyyy-MM-dd-HH-mm-ss)。
  2. 用格式化后的时间字符串拼接文件名,避免系统截断问题。

修改后的代码示例

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.NoSuchPaddingException;

public void txtEncrypt(String text, LocalDateTime localDateTime) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
    FileOutputStream outStream = null;
    try {
        // 定义无非法字符的时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedTime = localDateTime.format(formatter);
        
        String subfolder = "Encryption" + File.separator + "txt";
        // 使用格式化后的时间拼接文件名
        String fileName = formattedTime + "-encryptedText.txt";
        File file = new File(subfolder, fileName);
        // 自动创建不存在的父目录,避免文件创建失败
        file.getParentFile().mkdirs();
        outStream = new FileOutputStream(file);
        
        // 后续加密写入逻辑...
    } finally {
        // 确保流资源被关闭
        if (outStream != null) {
            outStream.close();
        }
    }
}

额外提示

  • 后续添加医生ID时,需确保ID不包含文件名非法字符(如/ \ : * ? " < > |),必要时可对ID做转义或过滤处理。
  • 调用file.getParentFile().mkdirs()能自动创建多层父目录,避免因目录不存在导致文件创建失败。

内容的提问来源于stack exchange,提问作者Yasiru Ruwantha Weerakoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:01:08