
在Java程序中复制文件时,可能会遇到java.nio.file.InvalidPathException,提示“Illegal char”错误。这通常是由于目标文件路径包含了在文件系统中不允许使用的字符导致的。本文将详细介绍如何避免此类错误,并提供清晰的代码示例和注意事项,帮助开发者安全有效地复制文件。
java.nio.file.InvalidPathException 异常表明你尝试创建的文件路径包含非法字符。在Windows系统中,常见非法字符包括 <、>、:、"、/、、|、?、* 等。在提供的代码示例中,异常信息显示非法字符为 :,位于时间格式化后的字符串中。
Exception in thread "AWT-EventQueue-0" java.nio.file.InvalidPathException: Illegal char <:> at index 2: D:\DOFN Materials\App\LMSystem\Copy\back14-11-2022 12:19:06_LMSystem
这段错误信息表明,由于在文件名中直接使用了包含冒号的时间字符串(例如 "12:19:06"),导致创建文件路径失败。
要解决此问题,需要确保生成的文件名不包含任何非法字符。以下是推荐的解决方案:
立即学习“Java免费学习笔记(深入)”;
以下是修改后的代码示例,展示了如何安全地复制文件并避免InvalidPathException:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class FileCopyExample {
public void copyFile() {
try {
// 1. 使用 java.time API 获取当前时间并格式化
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy_HH-mm-ss");
String formattedDate = now.format(formatter);
// 2. 定义源文件和目标文件路径
Path sourceFile = Paths.get("D:\DOFN Materials\App\LMSystem\LMSystem.sqlite");
//注意:这里使用Paths.get()替代new File()
// 3. 构建目标文件路径,并使用格式化后的日期时间字符串
Path destinationFile = Paths.get("D:\DOFN Materials\App\LMSystem\Copy\back" + formattedDate + "_LMSystem");
// 4. 复制文件
Files.copy(sourceFile, destinationFile, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully!");
JOptionPane.showMessageDialog(null, formattedDate + " Copy Successfully !!");
} catch (IOException ex) {
Logger.getLogger(FileCopyExample.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Error copying file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
FileCopyExample example = new FileCopyExample();
example.copyFile();
}
}代码解释:
通过使用java.time API进行日期时间格式化,移除或替换文件名中的非法字符,以及使用Paths.get()创建Path对象,可以有效地避免java.nio.file.InvalidPathException异常。同时,确保程序具有适当的文件权限和异常处理机制,可以提高程序的稳定性和可靠性。
以上就是解决Java文件复制时InvalidPathException:非法字符问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号