Read Write file IO using BufferedReader & BufferedWriter
- Given a file, read & write file contents using BufferReader & BufferWriter in java.
- Use java NIO (Non-Blocking or New IO) feature to perform java IO operations.
- BufferWriter writes to character based stream & BufferReader reads from character based stream, so as to provide efficient writing/reading of characters, arrays, and strings.
- We have already discussed similar posts:
- Java IO operation using BufferWriter & BufferReader (without NIO).
- Read & write file contents (UTF) using InputStreamReader/OutputStreamWriter.
- Read & write contents (without UTF) using InputStreamReader/OutputStreamWriter
Program – read & write file using BufferedReader & BufferedWriter (NIO)
package org.learn.io; import java.io.BufferedReader; 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 BufferReaderWriterNIO { public static void main(String[] args) throws IOException { writeUsingNIO(); readUsingNIO(); } private static void writeUsingNIO() throws IOException { System.out.println("1. Start writting contents to file - BufferedWriter(NIO)"); Path path = Paths.get("sampleFile.txt"); try (BufferedWriter bufferWriter = Files.newBufferedWriter(path)) { bufferWriter.write("Soccer"); bufferWriter.newLine(); bufferWriter.write("Tennis"); bufferWriter.newLine(); bufferWriter.write("Badminton"); bufferWriter.newLine(); bufferWriter.write("Hockey"); bufferWriter.newLine(); } System.out.println("2. Successfully written contents to file - BufferedWriter(NIO)"); } private static void readUsingNIO() throws IOException { Path path = Paths.get("sampleFile.txt"); try (BufferedReader bufferedReader = Files.newBufferedReader(path)) { String line; System.out.println("\n3. Start Reading file using BufferedReader (NIO)"); while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } System.out.println("4. End reading file using BufferedReader (NIO)"); } } }
The content of sampleFile.txt is as follows:
Output: Read & write file in java (BufferedReader & BufferedWriter)
1. Start writting contents to file - BufferedWriter(NIO) 2. Successfully written contents to file - BufferedWriter(NIO) 3. Start Reading file using BufferedReader (NIO) Soccer Tennis Badminton Hockey 4. End reading file using BufferedReader (NIO)