0

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.

tstorms
  • 4,941
  • 1
  • 25
  • 47
András Hummer
  • 960
  • 1
  • 17
  • 35

1 Answers1

1

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

user207421
  • 305,947
  • 44
  • 307
  • 483
  • I tried it, but the symptom's the very same: directories, subdirectories not created, `createNewFile()` throws `IOException`. Not to mention that `MY_SRC_DIR` already exists under `C:\xfer`. – András Hummer May 07 '13 at 10:21
  • You mean `mkdirs()` returns true but doesn't do anything? No actual directories created on the disk? – user207421 May 10 '13 at 00:38
  • No, mkdirs() returns false even though the parent directory already exists (was created earlier manually). – András Hummer May 10 '13 at 07:20