Site icon

BufferedReader & BufferedWriter (NIO) – Read & write file (java/example)

Read and write file in java

Fig 1: Contents of file

Read Write file IO using BufferedReader & BufferedWriter

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:

Fig 1: Write contents using BufferWriter

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)
Exit mobile version