在OSX和JVM 7上,FileChannel.open似乎被打破了

eka*_*aqu 12 java macos jvm

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

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
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的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)
Run Code Online (Sandbox Code Playgroud)

这是doc(或doc的解释)问题,还是OSX上的bug(甚至可能是linux?还没有测试过)?

Man*_*ari 15

您必须与CREATE_NEW一起指定WRITE.我刚刚在OS X上测试了这个,它按预期工作:

FileChannel.open(Paths.get("/tmp/doesnotexist"), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
Run Code Online (Sandbox Code Playgroud)