是否有一种简洁,惯用的方式(可能使用Apache Commons)来指定OpenOption的常见组合 StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING
这些都是您的轻松可能性.
静态导入,以提高可读性:
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);
警告:未经测试.