1

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

    }
4

1 回答 1

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);
于 2017-05-15T09:30:56.233 回答