Wednesday, July 1, 2009

In Java, how to change the encoding of files

These days, I have a task to change the file whose encoding is UTF-8 into a file with encoding of GBK.

I found a very useful tutorial at:
http://www.herongyang.com/unicode/jdk_encoding_conversion.html

As a summary, you can directly use the following Java code:

String cfilename="";
String outCnFileName="";

BufferedReader cfile = new BufferedReader( new InputStreamReader(new FileInputStream(cfilename),"UTF-8") );
BufferedWriter outcnfile = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outCnFileName),"GBK") );

String line=cfile.readLine();
while( line!=null )
{
outcnfile.write(line+"\n");
}

cfile.close();
outcnfile.close();

No comments: