13

我目前遇到的问题是我遇到了以前从未见过的异常​​,这就是为什么我不知道如何处理它。

我想根据给定的参数创建一个文件,但它不起作用。

public static Path createFile(String destDir, String fileName) throws IOException {
        FileAccess.createDirectory( destDir);

        Path xpath = new Path( destDir + Path.SEPARATOR + fileName);

        if (! xpath.toFile().exists()) {
            xpath.toFile().createNewFile();
            if(FileAccess.TRACE_FILE)Trace.println1("<<< createFile " + xpath.toString() );
        }
      return xpath;
  }


  public static void createDirectory(String destDir) {
      Path dirpath = new Path(destDir);
      if (! dirpath.toFile().exists()) {
          dirpath.toFile().mkdir();
          if(TRACE_FILE)Trace.println1("<<< mkdir " + dirpath.toString() );
      }
  }

每次我运行我的应用程序时,都会发生以下异常:

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

我该如何摆脱它?(我正在使用Win7 64位顺便说一句)

4

1 回答 1

18

问题是除非整个包含路径已经存在,否则无法创建文件 - 它的直接父目录和它上面的所有父目录。

如果你有一个路径 c:\Temp 并且它下面没有子目录,并且你尝试创建一个名为 c:\Temp\SubDir\myfile.txt 的文件,那将会失败,因为 C:\Temp\SubDir 不存在。

   xpath.toFile().createNewFile(); 

添加

   xpath.toFile().mkdirs(); 

(我不确定 mkdirs() 是否只需要对象中的路径;如果需要,则将该新行更改为

   new File(destDir).mkdirs();

否则,您会将文件名创建为子目录!您可以通过检查 Windows 资源管理器以查看它创建的目录来验证哪个是正确的。)

于 2012-03-07T10:29:48.947 回答