To open a file for writing in JDK 7 you can use the Files.newBufferedWriter()
method. This method takes three arguments. We need to pass the Path
, the Charset
and a varargs of OpenOption
.
For example, in the snippet below we pass the path of our log file, we use the StandardCharsets.UTF_8
charset, and we use the StandardOpenOption.WRITE
to open a file for writing. If you want to open a file and append its contents instead of rewriting it you can use the StandardOpenOption.APPEND
.
package org.kodejava.io;
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FilesNewBufferedWriter {
public static void main(String[] args) throws Exception {
Path logFile = Paths.get("app.log");
if (Files.notExists(logFile)) {
Files.createFile(logFile);
}
try (BufferedWriter writer =
Files.newBufferedWriter(logFile, StandardCharsets.UTF_8,
StandardOpenOption.WRITE)) {
for (int i = 0; i < 10; i++) {
writer.write(String.format("Message %s%n", i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Because we use the StandardOpenOption.WRITE
we have to make sure that the file to be written is exists. If the file is not available we will get error like java.nio.file.NoSuchFileException
.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
thank you!
Thank you. That saved me.