Search This Blog

Thursday, March 12, 2009

Read && Write To/From file UTF-8 characters in java

Here is the write method :


private void writeToFile(String data)
{
try {
File file = new File("C:\\TEMP\\chinese1.txt.html");
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file),"UTF8"));

bw.write(data);
bw.close();

} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}



Here is the read method


private String readFromFile()
{
String retStr="";
try {
File file = new File("C:\\TEMP\\chinese.txt.html");
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file),"UTF8"));

String s;
while((s = br.readLine()) != null) {
retStr += s;//new String(s.getBytes(),"UTF-8");
}
br.close();

} catch (IOException e1) {
e1.printStackTrace();
}
writeToFile(retStr);
return retStr;
}


Yaniv

No comments: