星期五, 三月 05, 2004

Java字符集之间转换

/**
*

Title:


*

Description:

Copyright: Copyright (c) 2004


*

Company: sos


* @author William Wang
* @version 1.0
*/
import java.io.*;

public class big2ucs {
public big2ucs() {
}
public static void main(String[] args) throws Exception
{
if(args.length<2){System.out.println("Syntax:big2ucs sourcefile(big5 format) outputfile");System.exit(0);}
System.out.println("Big5 source File is "+args[0]+" Unicode Format file is "+args[1]);
File sourcefile = new File(args[0]);
File outputfile = new File(args[1]);
FileInputStream is = new FileInputStream(sourcefile);
FileOutputStream os = new FileOutputStream(outputfile);
InputStreamReader isr = new InputStreamReader(is,"Big5-HKSCS");
BufferedReader br = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter(os,"UTF-16LE");
String buffstr="";
char[] line={0x0d,0x0a};
char[] readc=new char[30];
int isend;
do
{
buffstr=br.readLine();
if(buffstr != null)
{
osw.write(new String(buffstr.getBytes(),"UTF-16LE"));
//osw.write(buffstr);
osw.write("\n");
}
}while(buffstr != null);

//while((isend=isr.read())!=-1)osw.write(isend);

osw.flush();
is.close();
os.close();
isr.close();
br.close();

}
public static String convert(String pValue, String pEncoding)
throws IOException
{
byte bytes[] = getBytes(pValue);
return convert(bytes, pEncoding);
}
public static byte[] getBytes(String pValue)
{
byte bytes[] = new byte[pValue.length()];
for(int i = 0; i < bytes.length; i++)
bytes[i] = (byte)pValue.charAt(i);

return bytes;
}

public static String convert(byte pValue[], String pEncoding)
throws IOException
{
ByteArrayInputStream bais = new ByteArrayInputStream(pValue);
InputStreamReader isr = new InputStreamReader(bais, pEncoding);
StringBuffer sb = new StringBuffer();
for(int c = isr.read(); c != -1; c = isr.read())
sb.append((char)c);

return sb.toString();
}

}