Sunday, March 27, 2011

Reading and saving UTF8 text file in Java

To read and save text file in Java, we need to add the "UTF-8" parameter in the Stream Reader.


File file = new File("1.txt");
BufferedReader reader = null;
try {
   reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
   String text = reader.readLine();
   String s1="\u6df1\u6c34\u57d7";
   String s2="深水埗";

   OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("2.txt"),"UTF-8");
   out.write(text+s1+s2);
   out.flush();
   out.close();

} catch (Exception e) {
   e.printStackTrace();
}

No comments:

Post a Comment

CSP on Apache

To add CSP to root if sort of funny. The following will NOT work for most cases !!     <LocationMatch "^/$">        Header s...