Writing a file in UTF-8 Format using FileWriter

Hi,I am trying to write some data to the file system using a filewriter object. I want the file to be stored in UTF-8 encoding. Please give me some pointers regarding the same.Best Regards,Pradeep
[224 byte] By [bkpaddya] at [2007-10-1 8:21:04]
# 1

First you have to declare that you will use UTF8 :

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(myFilePath,true),"UTF8");

Then you can write in you file in UTF8.

The problem is that when you open the file with an editor like Crimson or UltraEdit, it says that your file is encoded in ASCII ... even if your stream had well been saved in UTF8.

To be sure that your file format is UTF8, you have to had at the beginning of your file 3 bytes : EF, BB and BF :

byte[] x = new byte[3];

x[0] = (byte) (Integer.parseInt("EF",16));

x[1] = (byte) (Integer.parseInt("BB",16));

x[2] = (byte) (Integer.parseInt("BF",16));

osw.write(new String(x,"UTF8"));

Here my "complete" code :

String myFilePath = "........";

String myText = "............";

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(myFilePath,true),"UTF8");

System.err.println("osw encoding : "+osw.getEncoding()); //just to be sure of the encoding

byte[] x = new byte[3];

x[0] = (byte) (Integer.parseInt("EF",16));

x[1] = (byte) (Integer.parseInt("BB",16));

x[2] = (byte) (Integer.parseInt("BF",16));

osw.write(new String(x,"UTF8"));

osw.write(new String(myText));

osw.close();

I think you can use OutputStreamWriter instead of FileWriter as FileWriter inherits of OutputStreamWriter.

Pimoussea at 2007-7-9 21:33:43 > top of Java-index,Desktop,I18N...