How to Read UTF-8 Encoded Data from a File in Java


In this example we will show how to read UTF-8 encoded data from a file in Java.

Source Code

package com.beginner.examples;

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

public class ReadFileByUTF8 {

	public static void main(String[] args) {
		try {
			FileInputStream input = new FileInputStream("E:tmpTest.txt");
			InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
			BufferedReader br = new BufferedReader(inputReader);
			String line = null;
			while((line = br.readLine()) !=null) {
				System.out.println(line);
			}
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(UnsupportedEncodingException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}

	}

}

Output:

Hello Wolrd!

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments