Is there a concise, idiomatic way (maybe using Apache Commons) to specify common combinations of OpenOption like StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING
Quickest way to use common OpenOption combinations
18k views Asked by Aleksandr Dubinsky AtThere are 3 answers
The best suggestion I can offer would be to cheat on the equivalence of T... and T[], which one of the other stackoverflow discussions says should work
Can I pass an array as arguments to a method with variable arguments in Java?
So...
OpenOption myOptions[] = {StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING};
OutputStream foo=OutputStream.newOutputStream(myPath,myOptions);
Caveat: Untested.
java.nio.file.Files
has 5 flavours of methods with OpenOption
varargs parameters:
Files
.newBufferedWriter(...)
.write(...)
.newOutputStream(...)
.newInputStream(...)
.newByteChannel(...)
They directly don't restrict any OpenOption
combination, but all of them under the hood call to some of these 3 methods at java.nio.file.spi.FileSystemProvider
:
FileSystemProvider
.newInputStream(Path, OpenOption...)
.newOutputStream(Path, OpenOption...)
.newByteChannel(Path, Set<? extends OpenOption>, FileAttribute<?>...)
FileSystemProvider.newInputStream(...)
is called by: Files.newInputStream(...)
FileSystemProvider.newOutputStream(...)
is called by:
Files
.newBufferedWriter(...)
.newOutputStream(...)
.write(...)
abstract FileSystemProvider.newByteChannel(...)
is called by:
Files.newByteChannel(...)
FileSystemProvider.newInputStream(...)
FileSystemProvider.newOutputStream(...)
OptenOption
combination restrictions:
- FileSystemProvider.newInputStream(...)
- UnsupportedOperationException: WRITE || APPEND
- FileSystemProvider.newOutputStream(...)
- Implicitly: WRITE
- IllegalArgumentException: READ
- default (if non options): CREATE && TRUNCATE_EXISTING
The abstract FileSystemProvider.newByteChannel(...)
method has a platform dependent implementation, which may extend the OpenOption
combination restrictions (as in sun.nio.fs.WindowsFileSystemProvider
).
All Files method which uses OpenOption
vargars under the hood ends in the abstract FileSystemProvider.newByteChannel(...)
, which implementation is platform dependent. So, the OpenOption
combinations restriction in Files methods are platform dependent.
These are the easy possibilities you have.
Static Imports, to increase readability:
Use defaults:
Finally it's possible to specify optionsets like this: