Read /write UTF contents to/ from file in java (BufferReader /BufferWriter /example)

  1. Given UTF contents, read & write utf contents using BufferReader & BufferWriter in java.
    1. Write UTF contents to the file using BufferWriter class in java.
    2. Read UTF contents from file using BufferReader class in java.
    3. Read & write contents without using java NIO feature.
  2. We have already discussed similar posts:
    • Read & write UTF file using BufferReader & BufferWriter (using NIO)
    • Read & write utf contents using InputStreamReader/OutputStreamWriter (without NIO)

1. Read/write UTF contents to/from file in java (BufferReader/BufferWriter)

package org.learn.utf.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class BufferReaderWriter {
 public static void main(String[] args) throws IOException {  
  writeUTFUsingBufferWriter();
  readUTFUsingBufferReader(); 
 }

 private static void writeUTFUsingBufferWriter() throws IOException {
  System.out.println("1. Start writing contents to file using BufferedWriter");
  try (FileOutputStream fileStream = new FileOutputStream(new File("sampleUTFFile.txt"));
    OutputStreamWriter writer = new OutputStreamWriter(fileStream, "UTF-8");
    BufferedWriter bufferWriter = new BufferedWriter(writer)) {
   bufferWriter.write("Names of Jackie Chan:");
   bufferWriter.newLine();
   bufferWriter.write("房仕龍 (Fong Si-lung)");
   bufferWriter.newLine();
   bufferWriter.write("元樓 (Yuen Lou)");
   bufferWriter.newLine();
   bufferWriter.write("大哥 (Big Brother)");
  }
  System.out.println("2. Successfully written contents to file using BufferedWriter");
 }
 
 private static void readUTFUsingBufferReader() throws IOException {
  try (FileInputStream fileStream = new FileInputStream(new File("sampleUTFFile.txt"));
    InputStreamReader reader = new InputStreamReader(fileStream, "UTF-8");
    BufferedReader bufferedReader = new BufferedReader(reader)) {
   System.out.println("\n3. Start Reading file contents using BufferedReader");
   String line;    
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
            System.out.println("4. End Reading file contents using BufferedReader");
  }
 }
}

2. Contents written to sampleUTFFile.txt file:

BufferWriter file IO example
Fig 1: Written contents using BufferWriter

3. OP: Read/write UTF contents to/from file (BufferReader/BufferWriter)

1. Start writing contents to file using BufferedWriter
2. Successfully written contents to file using BufferedWriter

3. Start Reading file contents using BufferedReader
Names of Jackie Chan:
房仕龍 (Fong Si-lung)
元樓 (Yuen Lou)
大哥 (Big Brother)
4. End Reading file contents using BufferedReader
Scroll to Top