Saturday, 8 June 2019

Java 8 | Write to file

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.

Example in Java 8 to write content:
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class WriteToFile {
       public static void main(String[] args) throws IOException {
              // Get the file reference
              Path path = Paths.get("Output.txt");
              // Use try-with-resources to get auto-closeable writer instance
              try (BufferedWriter writer = Files.newBufferedWriter(path)) {
                      writer.write("Hello World !!");
              }
       }
}

Write to file using Files.write()

Using Files.write() method is also pretty much clean code.

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class WriteToFile {

       public static void main(String[] args) throws IOException {
              String content = "Hello World !!";
              Files.write(Paths.get("Output1.txt"), content.getBytes());
       }
}

Above both methods are good for almost all use cases which need to write the file in Java 8.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...