2014-10-14 23 views
7

Trên OSX với JVM 7, tôi thấy rằng FileChannel.open với CREATE_NEW dường như không tuân thủ docs. Đoạn mã dưới đây, tôi hy vọng sẽ tạo một tệp mới và chỉ thất bại nếu nó không thể (quyền, vấn đề đĩa) hoặc tệp đã tồn tại.Trên OSX và JVM 7, FileChannel.open dường như bị hỏng

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 = [email protected] 

scala> FileChannel.open(path.toPath, StandardOpenOption.CREATE_NEW) 
res11: java.nio.channels.FileChannel = [email protected] 

scala> FileChannel.open(path.toPath, StandardOpenOption.CREATE_NEW) 
res12: java.nio.channels.FileChannel = sun.nio.ch.FileCha[email protected] 

Đây là Java mà tôi đang sử dụng

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

Đây có phải là một doc (hoặc giải thích doc) vấn đề, hoặc một lỗi trên OSX (thậm chí có thể linux? Không thử nghiệm nào)?

Trả lời

10

Bạn phải chỉ định WRITE cùng với CREATE_NEW. Tôi vừa thử nghiệm điều này trên OS X của tôi cho bạn và nó hoạt động như mong đợi:

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

Cảm ơn, đã hoạt động! – ekaqu

Các vấn đề liên quan