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

Java实现文件名扩展名前添加后缀功能的代码异常修正咨询

代码修改点整理

1. 配置文件路径读取适配需求

需求要求接收必填的配置文件路径参数,当前代码硬编码了配置路径,需改为从main方法入参args中读取:

if (args.length == 0) {
    // 可补充SEVERE日志提示缺少配置路径参数后终止
    System.exit(1);
}
String PATH_TO_PROPERTIES = args[0];

2. 修复字符串比较逻辑

Java中字符串相等判断不能用==/!=,需改为equals方法,避免判断失效:

// 原错误代码:if (mode != "copy")
if (!"copy".equals(mode)) {
    logging.log(Level.SEVERE, "Mode is not recognized: " + mode);
    System.exit(1);
}

3. 调整全局配置校验位置

当前把mode、suffix、files的全局校验写在文件遍历循环里,会重复执行,且出错后没有正确终止程序,需将这三类校验提到加载配置完成后、进入循环前,校验失败打日志后直接调用System.exit(1)终止执行。

4. 修复配置项校验逻辑

  • 原suffix判断错误调用了prop.getProperty(suffix),实际应该直接校验suffix变量本身是否为空:
// 原错误代码:else if (prop.getProperty(suffix) == "")
if (suffix == null || suffix.isBlank()) {
    logging.log(Level.SEVERE, "No suffix is configured");
    System.exit(1);
}
  • 原files判断逻辑错误,应该校验files变量是否为空,或分割后是否没有有效文件:
if (files == null || files.isBlank() || files.split(":").length == 0) {
    logging.log(Level.WARNING, "No files are configured to be copied/moved");
    System.exit(1);
}

5. 移除硬编码文件校验逻辑

当前硬编码了三个固定File对象判断存在性,完全没有校验循环中当前遍历的文件,需改为每次循环动态判断当前文件:

for (String filePath : files.split(":")) {
    File srcFile = new File(filePath);
    // 路径转正斜杠输出
    String standardPath = srcFile.getPath().replace("\\", "/");
    if (!srcFile.exists()) {
        logging.log(Level.SEVERE, "No such file: " + standardPath);
        continue; // 不终止其他文件处理
    }
    // 后续处理逻辑
}

6. 修复目标文件名&路径生成逻辑

  • 要处理无扩展名的文件,避免indexOf('.')返回-1时报错
  • 不要硬编码目标路径,复用源文件的父路径拼接
int dotIndex = filePath.lastIndexOf('.');
String newFileName;
if (dotIndex == -1) {
    newFileName = filePath + suffix;
} else {
    newFileName = filePath.substring(0, dotIndex) + "-" + suffix + filePath.substring(dotIndex);
}
File destFile = new File(srcFile.getParent(), newFileName);

7. 修复日志输出格式

复制日志只需要输出当前源文件和目标文件的正斜杠路径,不要输出全部文件列表:

String srcPath = srcFile.getPath().replace("\\", "/");
String destPath = destFile.getPath().replace("\\", "/");
logging.log(Level.INFO, srcPath + " -> " + destPath);

8. 补充资源管理&实际文件操作逻辑

  • 用try-with-resources自动管理FileInputStream,避免资源泄漏
  • 补充实际的文件复制逻辑,当前代码只有日志没有实际操作
// 原流读取改为自动关闭
try (FileInputStream fileInputStream = new FileInputStream(PATH_TO_PROPERTIES)) {
    prop.load(fileInputStream);
}
// 复制操作补充
Files.copy(srcFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

内容的提问来源于stack exchange,提问作者Petru Ciorba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:39:00