在带有JVM 7的OSX上,我看到带有CREATE_NEW的FileChannel.open似乎不符合docs。我希望在下面的代码中创建一个新文件,并且只有在它不能(权限,磁盘问题)或该文件已经存在时才会失败。

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)

这是文档(或文档的解释)问题,还是OSX上的错误(甚至是linux?尚未测试)?

最佳答案

您必须指定WRITE以及CREATE_NEW。我刚刚在OS X上为您测试过,它可以按预期工作:

FileChannel.open(Paths.get("/tmp/doesnotexist"), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);

10-06 11:52