2013-05-07 67 views
0

我想复制和现有的目录结构(不需要文件内容本身,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()); 

,但也不能工作。

+0

抛出什么IOException?什么信息? – EJP 2013-05-07 20:01:04

+0

对不起@EJP,我忘了它。请参阅更新的说明。 – 2013-05-08 07:29:46

回答

1

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

+0

我试过了,但是症状非常一致:目录,子目录未创建,'createNewFile()'抛出'IOException'。更不用说'C:\ xfer'下已经存在'MY_SRC_DIR'。 – 2013-05-07 10:21:42

+0

你的意思是'mkdirs()'返回true,但什么都不做?没有在磁盘上创建实际的目录? – EJP 2013-05-10 00:38:54

+0

不,即使父目录已经存在(已经手动创建),mkdirs()也会返回false。 – 2013-05-10 07:20:53