Quickest way to use common OpenOption combinations

Aleksandr Dubinsky picture Aleksandr Dubinsky · Dec 18, 2013 · Viewed 15.2k times · Source

Is there a concise, idiomatic way (maybe using Apache Commons) to specify common combinations of OpenOption like StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING

Answer

Franz Ebner picture Franz Ebner · Jan 1, 2014

These are the easy possibilities you have.

Static Imports, to increase readability:

import static java.nio.file.StandardOpenOption.CREATE_NEW;
import static java.nio.file.StandardOpenOption.WRITE;

OpenOption[] options = new OpenOption[] { WRITE, CREATE_NEW };

Use defaults:

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

Finally it's possible to specify optionsets like this:

     Files.newByteChannel(path, EnumSet.of(CREATE_NEW, WRITE));