Create new file or overwrite existing one with Files.newBufferedWriter in Java 7

file, java, java-7

Solution

The documentation of this function already says us that:

`newBufferedWriter(Path path, Charset cs, OpenOption... options)`

The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the `CREATE, TRUNCATE_EXISTING, and WRITE` options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.

So you could just do without passing an option:

BufferedWriter writer = Files.newBufferedWriter(Paths.get("example.txt"), 
                                                StandardCharsets.UTF_8);

Problem

I am giving a try to the new Files.newBufferedWriter in Java 7 and I can't get an example to work: I want to create a new file if it doesn't exist or overwrite it if it does. What I do is: ``` OpenOption[] options = {StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING}; BufferedWriter writer = Files.newBufferedWriter(Paths.get("example.txt"), StandardCharsets.UTF_8, options); ``` I tried also with different options, but I can't get it to work. Help?

Original source