我想複製和現有的目錄結構(不需要文件內容本身,0長度的虛擬文件將做)。但是mkdirs()
將不會創建必要的目錄,導致file.createNewFile()
拋出IOException
。該代碼是:java文件mkdirs和createNewFile不會工作
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());
,但也不能工作。
拋出什麼IOException?什麼信息? – EJP 2013-05-07 20:01:04
對不起@EJP,我忘了它。請參閱更新的說明。 – 2013-05-08 07:29:46