gpt4 book ai didi

Java 复制和粘贴文件 NoSuchFileException

转载 作者:行者123 更新时间:2023-11-30 06:43:56 25 4
gpt4 key购买 nike

尝试根据一个目录(字符串列表)中文件名的字符串搜索来复制和粘贴文件,根据搜索字符串创建一个新文件夹,然后将匹配的文件复制并粘贴到该文件夹​​时,我收到了 NoSuchFileException 。当我尝试了相当长一段时间后,有人能够发现这个问题吗?难道是文件路径太长了?

    File[] files = new File(strSrcDir).listFiles();

for (String term : list) {

for (File file : files) {
if (file.isFile()) {
String name = file.getName();
Pattern pn = Pattern.compile(term, Pattern.CASE_INSENSITIVE);
Matcher m = pn.matcher(name);
if (m.find()) {
try {
String strNewFile = "G:\\Testing\\" + type + "\\" + term + "\\" + name;
File newFile = new File(strNewFile);
Path newFilePath = newFile.toPath();
Path srcFilePath = file.toPath();
Files.copy(srcFilePath, newFilePath);
} catch (UnsupportedOperationException e) {
System.err.println(e);
} catch (FileAlreadyExistsException e) {
System.err.println(e);
} catch (DirectoryNotEmptyException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
} catch (SecurityException e) {
System.err.println(e);
}
}
}
}

}

最佳答案

String strNewFile = "G:\\Testing\\" + type + "\\" + term + "\\" + name;

可能目录树不存在,Java 不会为您创建它,您需要手动创建它。

你可以这样做:

new File("G:\\Testing\\" + type + "\\" + term).mkdirs(); // create the directory tree if it doesn't exist

String strNewFile = "G:\\Testing\\" + type + "\\" + term + "\\" + name;
File newFile = new File(strNewFile);
Path newFilePath = newFile.toPath();
Path srcFilePath = file.toPath();
Files.copy(srcFilePath, newFilePath);

关于Java 复制和粘贴文件 NoSuchFileException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com