How to Read UTF-8 data from File in Java ?

DeeKay June 10, 2012 at 11:08 pm · java.io

Below Java Code shows how to read UTF-8 data from file or read UTF-8 encoded data from a text file-

/****************************************************************************************
 * Created on 06-2012 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * Created by http://kodehelp.com
 * Date: 6/9/12
 */
public class ReadUTF8DataFromFile {
    public static void main(String args[]){
        try {
            File fileDir = new File("c:\\Sample.txt");

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(fileDir), "UTF8"));

            String str;

            while ((str = in.readLine()) != null) {
                System.out.println(str);
            }

            in.close();
        }catch (UnsupportedEncodingException e){
            System.out.println(e.getMessage());
        }catch (IOException e){
            System.out.println(e.getMessage());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}