How to read UTF-8 encoded data from a file – Java
A text file with UTF-8 encoded data

P.S File is created by this article How to write UTF-8 encoded data into a file
Here’s the example to demonstrate how to read “UTF-8″ encoded data from a file in Java
package com.mkyong; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class test { public static void main(String[] args){ try { File fileDir = new File("c:\\temp\\test.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()); } } }
Result
Website UTF-8 ?? UTF-8 ??????? UTF-8
Do not worry about the symbol “???”, this is because my output console is not support the UTF-8 data. The variable “str” is storing exactly same “UTF-8″ encoded data as showed in the text file.
I just want to ask why you put a lot of catch statements wherein you already put a generalized catch statement at the bottom?
sorry, I am still a newbie~
this is a real stupidity that i can’t post UTF-8 string to explain the problem in code
This code doesn’t guarantee that it’ll read perfectly always.
for ex the word ?????? is being read as ??????
a ? symbol is prepended .. and for some others the same symbol was being appended
[...] Read UTF-8 encoded data from a file [...]