Read & write UTF file – BufferReader & BufferWriter (NIO & example)

  • Given the UTF contents, read & write utf contents using BufferReader & BufferWriter.
  • Use java nio feature to create BufferReader & BufferWriter.
  • We have already discussed similar posts:
    • Read & write contents bufferReader/bufferWriter without UTF using NIO
    • Read & write utf contents bufferReader/bufferWriter without NIO
    • Read & write utf contents InputStreamReader/OutputStreamWriter without NIO

In this post, we will demonstrate read and write operations with UTF-8 contents.
Let us look into the complete example code, where we are writing the contents to file and reading the contents from file (using NIO).

Program – Read & write UTF file (BufferReader & BufferWriter)

package org.learn.utf.io;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
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 {
        writeUTFUsingNIO();
        readUTFUsingNIO();
    }
 
    private static void writeUTFUsingNIO() throws IOException {
        Path path = Paths.get("sampleUTFFile.txt");
        System.out.println("1. Start writting contents to file - BufferedWriter(NIO)");
        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
            writer.write("Names of Jackie Chan:");
            writer.newLine();
            writer.write("房仕龍 (Fong Si-lung)");
            writer.newLine();
            writer.write("元樓 (Yuen Lou)");
            writer.newLine();
            writer.write("大哥 (Big Brother)");
        }
        System.out.println("2. Successfully written contents to file - BufferedWriter(NIO)");      
    }
 
    private static void readUTFUsingNIO() throws IOException {
        Path path = Paths.get("sampleUTFFile.txt");
        try (BufferedReader bufferedReader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            String line;
            System.out.println("\n3. Start Reading file - BufferedReader (NIO):");
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
            System.out.println("4. End reading file - BufferedReader (NIO)");
        }
    }
}

The content of sampleUTFFile.txt is as follows:

BufferWriter java file write
Fig 1: Written contents using BufferWriter(NIO)

Output – Read & write UTF file (BufferReader & BufferWriter)

1. Start writting contents to file - BufferedWriter(NIO)
2. Successfully written contents to file - BufferedWriter(NIO)
 
3. Start Reading file - BufferedReader(NIO):
Names of Jackie Chan:
房仕龍 (Fong Si-lung)
元樓 (Yuen Lou)
大哥 (Big Brother)
4. End reading file - BufferedReader(NIO)