Java 复制和粘贴文件 NoSuchFileException
Java copy and paste files NoSuchFileException
我尝试根据一个目录(字符串列表)中文件名的字符串搜索复制和粘贴文件时收到 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);
我尝试根据一个目录(字符串列表)中文件名的字符串搜索复制和粘贴文件时收到 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);