Java NIO is a preferred non blocking alternative to traditional JAVA I/O library for I/O operations. We can read and write using the Files utility provided by Java NIO.
In non blocking approach, calling threads can perform other tasks while read and write methods wait for their operations to complete. This is a significant performance improvement over the traditional Java I/O package.
Read File
public static void readFile() throws IOException {
BufferedReader reader = null;
try {
Path inputFile = Paths.get("input.txt");
reader = Files.newBufferedReader(inputFile, Charset.defaultCharset());
String lineFromFile = "";
while ((lineFromFile = reader.readLine()) != null) {
System.out.println(lineFromFile);
}
} catch (IOException e){
System.out.println(e);
} finally {
if(reader != null)
reader.close();
}
}
Write File
public static void writeFile() throws IOException {
BufferedWriter writer = null;
try {
Path outputFile = Paths.get("output.txt");
writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset());
StringBuilder message = new StringBuilder("This is a message going into the file.");
writer.append(message);
} catch (IOException e){
System.out.println(e);
} finally {
if(writer != null)
writer.close();
}
}