学文本处理,对文本的乱码问题是很头疼的。
今天弄Lucene的时候,又遇到了这个问题,我就想,能不能预先获得文件的编码方式呢?
事实证明是可以的。
这里涉及到文件头信息的问题,至于其中的原理,我在网上搜索了一下,也没有弄明白。
只是找到的段代码:
- package com.xh;
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.InputStreamReader;
- public class DetectingFileCoding {
- /**
- * 判断文件的编码格式
- * @param fileName :file
- * @return 文件编码格式
- * @throws Exception
- */
- public static String codeString(String fileName) throws Exception{
- BufferedInputStream bin = new BufferedInputStream(
- new FileInputStream(fileName));
- int p = (bin.read() << 8) + bin.read();
- String code = null;
- switch (p) {
- case 0xefbb:
- code = "UTF-8";
- break;
- case 0xfffe:
- code = "Unicode";
- break;
- case 0xfeff:
- code = "UTF-16BE";
- break;
- default:
- code = "GBK";
- }
- return code;
- }
- public String getContent(String file) {
- try {
- FileInputStream fInputStream = new FileInputStream(file);
- //code为上面方法里返回的编码方式
- InputStreamReader inputStreamReader = new InputStreamReader(fInputStream, codeString(file));
- BufferedReader in = new BufferedReader(inputStreamReader);
- StringBuffer sBuffer=new StringBuffer();
- String strTmp = "";
- //按行读取
- while (( strTmp = in.readLine()) != null) {
- sBuffer.append(strTmp + "/n");
- }
- in.close();
- inputStreamReader.close();
- fInputStream.close();
- return sBuffer.toString();
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- return null;
- }
- }
- public static void main(String[] args) {
- DetectingFileCoding DFC=new DetectingFileCoding();
- System.out.println(DFC.getContent("gbkfile.txt"));
- System.out.println(DFC.getContent("utf-8file.txt"));
- System.out.println(DFC.getContent("unicodefile.txt"));
- }
- }
我自己创建了三个txt文件,都放到Project的根目录下,截图如下:
程序运行结果如下:
不管怎么样,这也不失为一种处理文件的方法:
源程序来自于:http://blog.csdn.net/paul630/article/details/6164390