当我试图在一个目录(字符串列表)中基于文件名的字符串搜索复制和粘贴文件时,我收到了一个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);
}
}
}
}
}发布于 2017-05-15 09:30:56
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);https://stackoverflow.com/questions/43975783
复制相似问题