尝试根据一个目录(字符串列表)中文件名的字符串搜索来复制和粘贴文件,根据搜索字符串创建一个新文件夹,然后将匹配的文件复制并粘贴到该文件夹时,我收到了 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/