Java 在OSX和JVM7上,FileChannel.open似乎已损坏
在使用JVM7的OSX上,我发现使用CREATE_NEW的FileChannel.open似乎不符合。在下面的代码中,我希望创建一个新文件,只有当它不能(权限、磁盘问题)或文件已经存在时,才会失败Java 在OSX和JVM7上,FileChannel.open似乎已损坏,java,macos,jvm,Java,Macos,Jvm,在使用JVM7的OSX上,我发现使用CREATE_NEW的FileChannel.open似乎不符合。在下面的代码中,我希望创建一个新文件,只有当它不能(权限、磁盘问题)或文件已经存在时,才会失败 scala> FileChannel.open(new File("/tmp/doesnotexist").toPath, StandardOpenOption.CREATE_NEW) java.nio.file.NoSuchFileException: /tmp/doesnotexist
scala> FileChannel.open(new File("/tmp/doesnotexist").toPath, StandardOpenOption.CREATE_NEW)
java.nio.file.NoSuchFileException: /tmp/doesnotexist
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newFileChannel(UnixFileSystemProvider.java:177)
at java.nio.channels.FileChannel.open(FileChannel.java:287)
at java.nio.channels.FileChannel.open(FileChannel.java:334)
... 32 elided
scala> val path = new File("/tmp/doesnotexist")
path: java.io.File = /tmp/doesnotexist
scala> path.createNewFile()
res9: Boolean = true
scala> FileChannel.open(path.toPath, StandardOpenOption.CREATE_NEW)
res10: java.nio.channels.FileChannel = sun.nio.ch.FileChannelImpl@19fed8d0
scala> FileChannel.open(path.toPath, StandardOpenOption.CREATE_NEW)
res11: java.nio.channels.FileChannel = sun.nio.ch.FileChannelImpl@5c6ff75
scala> FileChannel.open(path.toPath, StandardOpenOption.CREATE_NEW)
res12: java.nio.channels.FileChannel = sun.nio.ch.FileChannelImpl@1fa547d1
这是我正在使用的Java
$ java -version
java version "1.7.0_55"
Java(TM) SE Runtime Environment (build 1.7.0_55-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.55-b03, mixed mode)
这是一个doc(或doc的解释)问题,还是OSX上的一个bug(甚至可能是linux?尚未测试)?您必须指定WRITE和CREATE\u NEW。我刚刚在我的OS X上为您测试了这一点,它按预期工作:
FileChannel.open(Paths.get("/tmp/doesnotexist"), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
这并不是这个问题的具体答案,因为我确信/tmp在您的系统上存在,但一般来说,您需要确保父目录也已经存在。如果一个或多个父目录不存在,您将得到相同的异常。在看到解决方案后,这似乎是显而易见的。但是,当我想创建一个(锁定的)文件而不写入它时,它就不是那么简单了。