是否有一种简洁、惯用的方式(可能使用 Apache Commons)来指定 OpenOption 的常见组合,例如StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING
3 回答
这些是您拥有的简单可能性。
静态导入,以增加可读性:
import static java.nio.file.StandardOpenOption.CREATE_NEW;
import static java.nio.file.StandardOpenOption.WRITE;
OpenOption[] options = new OpenOption[] { WRITE, CREATE_NEW };
使用默认值:
//no Options anyway
Files.newBufferedReader(path, cs)
//default: CREATE, TRUNCATE_EXISTING, and WRITE not allowed: READ
Files.newBufferedWriter(path, cs, options)
//default: READ not allowed: WRITE
Files.newInputStream(path, options)
//default: CREATE, TRUNCATE_EXISTING, and WRITE not allowed: READ
Files.newOutputStream(path, options)
//default: READ do whatever you want
Files.newByteChannel(path, options)
最后,可以像这样指定选项集:
Files.newByteChannel(path, EnumSet.of(CREATE_NEW, WRITE));
我能提供的最好的建议是欺骗 T... 和 T[] 的等价性,其他 stackoverflow 讨论之一说应该有效
我可以将数组作为参数传递给 Java 中具有可变参数的方法吗?
所以...
OpenOption myOptions[] = {StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING};
OutputStream foo=OutputStream.newOutputStream(myPath,myOptions);
警告:未经测试。
java.nio.file.Files
有 5 种带有OpenOption
可变参数的方法:
Files
.newBufferedWriter(...)
.write(...)
.newOutputStream(...)
.newInputStream(...)
.newByteChannel(...)
它们直接不限制任何OpenOption
组合,但它们都在后台调用以下 3 种方法中的一些方法java.nio.file.spi.FileSystemProvider
:
FileSystemProvider
.newInputStream(Path, OpenOption...)
.newOutputStream(Path, OpenOption...)
.newByteChannel(Path, Set<? extends OpenOption>, FileAttribute<?>...)
FileSystemProvider.newInputStream(...)
被调用:Files.newInputStream(...)
FileSystemProvider.newOutputStream(...)
被调用:
Files
.newBufferedWriter(...)
.newOutputStream(...)
.write(...)
抽象FileSystemProvider.newByteChannel(...)
被调用:
Files.newByteChannel(...)
FileSystemProvider.newInputStream(...)
FileSystemProvider.newOutputStream(...)
OptenOption
组合限制:
- FileSystemProvider.newInputStream(...)
- UnsupportedOperationException: 写 || 附加
- FileSystemProvider.newOutputStream(...)
- 隐式:写
- IllegalArgumentException: 读
- 默认(如果没有选项):CREATE && TRUNCATE_EXISTING
抽象 FileSystemProvider.newByteChannel(...)
方法有一个依赖于平台的实现,它可以扩展组合OpenOption
限制(如 中sun.nio.fs.WindowsFileSystemProvider
)。
OpenOption
所有在后台使用vargars 的Files 方法都以abstract 结尾FileSystemProvider.newByteChannel(...)
,该实现取决于平台。因此,OpenOption
Files 方法中的组合限制取决于平台。