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

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?

Answers


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

Need Your Help

Is there some "Feature Graphic" generator for Google Play?

android google-play

I'm looking for some "Feature Graphic" online generator. Feature Graphic is the big image displayed in the web-based Android Market.

Object comparison in JavaScript

javascript object comparison object-comparison

What is the best way to compare objects in JavaScript?