简体   繁体   中英

java File mkdirs and createNewFile won't work

I'm trying to copy and existing directory structure (no need for the file contents themselves, 0 length dummy files will do). However mkdirs() won't create the necessary directories, causing file.createNewFile() to throw an IOException . The code is:

private static void readAndCopy(File fileToCopy) throws IOException {
    File localVersion = new File(fileToCopy.getCanonicalPath().replace("O:\\", "C:\\xfer\\"));
    System.out.println("Replicating " + fileToCopy.getCanonicalPath() + " to " + localVersion.getCanonicalPath());

    if (fileToCopy.isDirectory()) {
        boolean dirCreated = localVersion.getParentFile().mkdirs();
        System.out.println(localVersion.getCanonicalPath() + " " + (dirCreated ? "" : "not ") + "created");

        if (dirCreated) {
            for (File content : fileToCopy.listFiles()) {
                readAndCopy(content);
            }
        }

    } else {
        if (!localVersion.exists()) {
            localVersion.createNewFile();
        }
    }
}

public static void main(String[] args) throws IOException {
    readAndCopy(new File("o:\\MY_SRC_DIR"));
}

The error message is:

java.io.IOException: The system cannot find the path specified
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(Unknown Source)

I also tried

File origParentFile = fileToCopy.getParentFile();
File newParent = new File(origParentFile.getCanonicalPath().replace("O:\\", "C:\\xfer\\"));
localVersion = new File(newParent, fileToCopy.getName());

, but that didn't work either.

You are mistaken. 'mkdirs() is creating all the directories including the file name itself as a directory. You need to call is creating all the directories including the file name itself as a directory. You need to call localVersion.getParentFile().mkdirs().`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM