Java 复制和粘贴文件 NoSuchFileException

标签 java copy 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);

关于Java 复制和粘贴文件 NoSuchFileException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975783/

相关文章:

java - 如何预处理 Spring Web 应用程序中的所有请求?

java - "or"嵌入文档java中的条件

java - Heavy DB 读写操作的设计选项

Java 单元测试 - 如何使用 mockito 答案对异步方法(使用回调)进行单元测试

python-3.x - 如何使用独立于平台的实现在 Python 中复制文件夹及其内容(文件/子目录)

c++ - 如何将 map 中的 copy_if 复制到 vector ?

c++ - 引用传递的参数的行为类似于拷贝

java - Files.copy 抛出 java.nio.file.NoSuchFileException 即使要复制的文件确实存在

java - 无法从 Java 中删除命名管道

Cygwin/cygdrive/c 没有这样的文件或目录