首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NoSuchFileException文件复制和粘贴

NoSuchFileException文件复制和粘贴
EN

Stack Overflow用户
提问于 2017-05-15 09:25:56
回答 1查看 1.3K关注 0票数 1

当我试图在一个目录(字符串列表)中基于文件名的字符串搜索复制和粘贴文件时,我收到了一个NoSuchFileException,它创建了一个基于搜索字符串的新文件夹,而不是将匹配的文件复制和粘贴到该文件夹。有人能发现这个问题,因为我已经尝试了很长一段时间吗?是不是文件路径太长了?

代码语言:javascript
复制
    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);
                    }
                }
            }
        }

    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-15 09:30:56

代码语言:javascript
复制
String strNewFile = "G:\\Testing\\" + type + "\\" + term + "\\" + name;

目录树可能不存在,而且Java不会为您创建目录树,您需要手动创建它。

你可以这样做:

代码语言:javascript
复制
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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43975783

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档