简体   繁体   中英

On OSX and JVM 7, FileChannel.open seems to be broken

On OSX with JVM 7, I am seeing that FileChannel.open with CREATE_NEW doesn't seem to comply with the docs . The code below, I would expect to create a new file, and only fail if it can't (permissions, disk issue) or that the file already exists.

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

Here is the Java that I am using

$ 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)

Is this a doc (or interpretation of doc) issue, or a bug on OSX (maybe even linux? Not tested yet)?

You must specify WRITE along with CREATE_NEW. I just tested this on my OS X for you, and it works as expected:

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

Not the answer to this problem in particular, because I'm sure /tmp exists on your system, but in general, you need to ensure that the parent directories already exist as well. If one or more of the parent directories doesn't exist, you'll get the same exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM