File.createNewFile()thowing IOException没有这样的文件或目录

我有一个写入日志文件的方法。 如果文件存在,它应该附加到它,如果没有,那么我希望它创建一个新文件。

if (!file.exists() && !file.createNewFile()) { System.err.println("Error with output file: " + outFile + "\nCannot create new file."); continue; } 

我有这个来检查是否可以创建一个文件。 file是一个java.io.File对象。 createNewFile抛出IOException:没有这样的文件或目录。 自从我几周前写这篇文章以来,这种方法一直运作良好,并且最近才开始这样做,尽管我不知道我能改变什么。 我已经检查过,目录存在,我对它有写权限,但后来我认为如果它因任何原因无法生成文件,它应该返回false。

有什么我不想让这个工作吗?

通常这是你最近改变的东西,首先是你的示例代码,如果不是文件存在而不是创建新文件 – 你试图编写代码 – 它是什么?

然后,查看目录列表以查看它是否确实存在,并在文件对象上执行println / toString(),对exception执行getMessage(),以及打印堆栈跟踪。

然后,再次从零知识开始,并从您使用的每个步骤重新考虑到这里。 这可能是你在某处某处陷入困境而在代码中进行概念化(因为它工作正常) – 你只是详细地追溯每一步,你会发现它。

尝试确保父目录存在:

 file.getParentFile().mkdirs() 

也许创建文件的目录不存在?

根据[java docs]( http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#createNewFile() ), createNewFile将以primefaces方式为您创建一个新文件。

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

鉴于createNewFile是primefaces的并且不会覆盖现有文件,您可以将代码重写为

 try { if(!file.createNewFile()) { System.out.println("File already exists"); } } catch (IOException ex) { System.out.println(ex); } 

这可能使任何潜在的线程问题,竞争条件等更容易被发现。

我认为您获得的exception可能是primefaces方法file.createNewFile()的文件检查的结果。 该方法无法检查文件是否存在,因为某些父目录不存在或您无权访问它们。 我建议这样:

 if (file.getParentFile() != null && !file.getParentFile().mkDirs()) { // handle permission problems here } // either no parent directories there or we have created missing directories if (file.createNewFile() || file.isFile()) { // ready to write your content } else { // handle directory here } 

如果考虑并发性,所有这些检查都是无用的,因为在每种情况下,某些其他线程都能够创建,删除或对您的文件执行任何其他操作。 在这种情况下,你必须使用我不建议做的文件锁;)

你当然得到这个例外‘系统找不到指定的路径’

只需打印’file.getAbsoluteFile()’,这将告诉您要创建的文件是什么。

如果您创建文件的目录不存在,则会发生此exception

这可能是一个线程问题 (一起检查和创建不是primefaces的: !file.exists() && !file.createNewFile() )或“文件” 已经是一个目录

试试( file.isFile() ):

 if (file.exists() && !file.isFile()){ //handle directory is there }else if(!file.createNewFile()) { //as before } 

在我的情况下,只是缺乏许可: