我正在尝试复制现有的目录结构(不需要文件内容本身,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());
,但这也不起作用。