Search code examples
javanionio2

Quickest way to use common OpenOption combinations


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


Solution

  • 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));