Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file

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?

like image 783
diminuta Avatar asked Nov 29 '13 18:11

diminuta


People also ask

How do you overwrite a file if it already exists in Java?

write("some text"); It will create a file abc. txt if it doesn't exist. If it does, it will overwrite the file.

Does BufferedWriter overwrite?

new BufferedWriter(output); or "write", you are overwriting the "output" file. Try to make sure you only declare a new BufferedWriter once throughout the course of the program, and append() to the file instead of write().


1 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);
like image 188
Sage Avatar answered Sep 29 '22 14:09

Sage