java文件mkdirs和createNewFile将无法正常工作

时间:2013-05-07 09:27:01

标签: java file-io ioexception java-io mkdirs

我正在尝试复制和现有的目录结构(不需要文件内容本身,0长度的虚拟文件会这样做)。但是mkdirs()不会创建必要的目录,导致file.createNewFile()抛出IOException。代码是:

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

错误消息是:

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

我也试过

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

,但这也不起作用。

1 个答案:

答案 0 :(得分:1)

你错了。 “mkdirs()is creating all the directories including the file name itself as a directory. You need to call localVersion.getParentFile()。mkdirs()。`

相关问题