Java 8 example to content into file. You may find examples of reading files using java 8 APIs in linked blog post.
1. Java 8 write to file using BufferedWriter
BufferedWriter is used to write text to a character or byte stream. Before printing the characters, it stores the characters in buffer and print in bunches. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.
Java program to write content to file using Java 8 APIs is –
//Get the file reference Path path = Paths.get("c:/output.txt"); //Use try-with-resource to get auto-closeable writer instance try (BufferedWriter writer = Files.newBufferedWriter(path)) { writer.write("Hello World !!"); }
2. Write to file using Files.write()
Using Files.write() method is also pretty much clean code.
String content = "Hello World !!"; Files.write(Paths.get("c:/output.txt"), content.getBytes());
Above both methods are good for almost all use cases which needs to write file in Java 8.
Happy Learning !!