我正在尝试复制现有目录结构(不需要文件内容本身,长度为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());
,但这也不起作用。
最佳答案
你误会了。 'mkdirs()is creating all the directories including the file name itself as a directory. You need to call
localVersion.getParentFile()。mkdirs()。