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?
write("some text"); It will create a file abc. txt if it doesn't exist. If it does, it will overwrite the file.
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().
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With