在使用 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?尚未测试)?
最佳答案
您必须与 CREATE_NEW 一起指定 WRITE。我刚刚在我的 OS X 上为您测试了这个,它按预期工作:
FileChannel.open(Paths.get("/tmp/doesnotexist"), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
关于java - 在 OSX 和 JVM 7 上,FileChannel.open 似乎已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26367081/