Search code examples
javacopynosuchfileexception

Java copy and paste files NoSuchFileException


I received a NoSuchFileException when trying to copy and paste files based on string search of filenames in one directory (a list of strings), create a new folder based on the search string, than copy and paste the matching files to that folder. Would anyone be able to spot the issue with this as I have tried for quite some time? Could it be the file paths are too long?

    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);
                    }
                }
            }
        }

    }

Solution

  • String strNewFile = "G:\\Testing\\" + type + "\\" + term + "\\" + name;
    

    Likely the directory tree doesn't exist, and Java won't create it for you, you need to create it manually.

    You can do like this:

    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);