OpenOption acts like a configuration when you open or create files using
There are mainly two different sets of OpenOptions are available in Java, below classes implements the interface
- StandardOpenOption, this class has set of standard open options.
- LinkOpenOption, this class has the options as to how symbolic links are handled.
- This option is used to open the file for read access.
- Below is an example code that opens file for read access.
Note: READ is a default option for all read methods, so its not necessary to pass it explicitly.
- This option tells the system to create a new file and if the file already exists, then fail.
- Below is an example code, It always tries to create a new file and if the file already exists, then it throws
.
- This option tells the system to create a new file only if it doesn't exist. If you pass both CREATE and CREATE_NEW as OpenOptions parameters, then CREATE_NEW option takes precedence.
- Below is an example code to create a new file if it doesn't exist.
- This option is used to open the file for write access.
- Below is an example code that opens file for write access (WRITE is a default option for all write methods, so its not necessary to pass it explicitly).
- This option is used to tell system to append the content.
- Below is an example code that appends text content.
- This option tell thats if the file already exists and it is opened for WRITE access, then its length is truncated to 0.
- This option is ignored if the file is opened only for READ access.
- Below is an example code that truncates existing content (i.e. length is set to zero, meaning that discarding all of its content) and writes new content.
- This option tells the system that the file is a Sparse file, when used with CREATE_NEW option, this provides a hint that the new file will be a sparse file.
- This option is ignored if the file system does not support sparse files.
- Below is an example code that truncates existing content (i.e. length is set to zero, in otherworks makes the file empty) and writes new content.
- This option tells the system that all the data (file data and meta data managed by file system) will be written synchronously.
- This option tells the system that the file data will be written synchronously.
- This option tells the system to delete the file.
- It makes the best effort to delete the file when appropriate
method is called, if the method is not called then a best effort attempt is made to try and delete the file when JVM terminates.
- This option tells the system not to follow symbolic links.
- By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Above examples source code can be found at