最近在做一个能分析网站新闻的网络爬虫,对方要求中文的新闻信息用UTF-8存储。可是国内大部分新闻网站的网页源代码里的中文都是GB2312 的,所以必须转成UTF-8.在网上搜了很多方法,有人自己写的,有人用String newcontent=new String(content.getBytes("GBK"),"UTF-8");这种方法,可是试过之后,好好的汉字都变成了乱码。于是到搜了一下英 文网页,很快就找到了解决之道。缺点是不是直接在内存中进行转换,而是把以GBK编码存储的文件转换成以UTF-8编码存储的文件。不管怎么说,能解决我的问题就好。(GB2312是GBK的子集,解决了GBK就解决了GB2312,在我这个项目里,由于GB2312不能正常显示某些不常用字,所以我使用了GBK)
英文网址如下,有兴趣的朋友可以看一下:http://www.chinesecomputing.com/programming/java.html
我把代码贴过来。convert(String infile, String outfile, String from, String to)函数就是转换函数,其中infile是要转换的文件路径,outfile是转换后存储的文件路径,from是infile的字符集,对应我的项目就 是GBK, to是outfile的字符集,对应我的项目就是UTF-8.
注意infile和outfile不能为相同路径,否则最后转换出的文件会是空文件。
import java.io.*;
public class inputtest {
public static void main(String[] args) {
String outfile = null;
try { convert(args[0], args[1], "GBK", "UTF8"); } // or "GB2312" or "BIG5"
catch (Exception e) {
System.out.print(e.getMessage());
System.exit(1);
}
}
public static void convert(String infile, String outfile, String from, String to)
throws IOException, UnsupportedEncodingException
{
// set up byte streams
InputStream in;
if (infile != null) in = new FileInputStream(infile);
else in = System.in;
OutputStream out;
if (outfile != null) out = new FileOutputStream(outfile);
else out = System.out;
// Use default encoding if no encoding is specified.
if (from == null) from = System.getProperty("file.encoding");
if (to == null) to = System.getProperty("file.encoding");
// Set up character stream
Reader r = new BufferedReader(new InputStreamReader(in, from));
Writer w = new BufferedWriter(new OutputStreamWriter(out, to));
// Copy characters from input to output. The InputStreamReader
// converts from the input encoding to Unicode,, and the OutputStreamWriter
// converts from Unicode to the output encoding. Characters that cannot be
// represented in the output encoding are output as '?'
char[] buffer = new char[4096];
int len;
while((len = r.read(buffer)) != -1)
w.write(buffer, 0, len);
r.close();
w.flush();
w.close();
}
}
转换后可以用“秀丸”这个文字编辑工具查看转换前后文字的编码。
有时候中文网页难以搜到答案时,去一下英文网页,也许答案马上就出来了~因此,学好英文是必要的。