我尝试根据文件名在一个目录(字符串列表)中搜索文件名来复制和粘贴文件时收到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);
}
}
}
}
}
答案 0 :(得分:1)
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);