Java操作本地文件时报java.nio.file.NoSuchFileException如何解决
问题解决方案
常见排查点
- 先验证源路径有效性:在代码中加入
System.out.println(Files.exists(Paths.get(sourcePath)));确认路径可被Java进程识别。Mac系统下需注意两个常见问题:一是路径大小写匹配,即使文件系统默认大小写不敏感,错误的大小写仍可能触发路径识别异常;二是系统隐私权限限制,可前往「系统设置>隐私与安全性>完全磁盘访问」,给对应的IDE或Java运行环境开启权限。 - 确认权限配置:执行
sudo ls -ld /Users/myname/Documents/myfolder/F24/archive检查Java进程对源目录有可读权限、对目标目录有可写权限。 - 现有代码仅支持单个文件拷贝:
java.nio.file.Files.copy原生不支持递归拷贝目录,如果你传入的sourcePath是目录路径,直接调用该方法会抛出NoSuchFileException或DirectoryNotEmptyException异常。
支持目录+文件拷贝的修改后代码
import java.nio.file.*; import java.nio.file.StandardCopyOption; public static boolean copyFile(String sourcePath, String targetPath){ boolean fileCopied = true; try{ Path source = Paths.get(sourcePath); Path target = Paths.get(targetPath); if(Files.isDirectory(source)){ // 目标目录不存在则自动创建 if(!Files.exists(target)){ Files.createDirectories(target); } // 递归遍历拷贝目录下所有内容 try(DirectoryStream<Path> stream = Files.newDirectoryStream(source)){ for(Path entry : stream){ Path entryTarget = target.resolve(entry.getFileName()); if(!copyFile(entry.toString(), entryTarget.toString())){ fileCopied = false; break; } } } }else{ // 拷贝单个文件 Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); } }catch(Exception e){ fileCopied = false; System.out.println("无法将文件从 "+sourcePath+" 拷贝到 "+targetPath+" ! \n"); e.printStackTrace(); } return fileCopied; }
调用注意事项
调用方法时传入的路径不要带多余的末尾斜杠,直接使用/Users/myname/Documents/myfolder/F24/archive格式即可,避免路径解析异常。
内容的提问来源于stack exchange,提问作者64Bit1990
相关产品推荐
相关产品推荐

