用java 要获得一个文件的编码,是很困难的,在网上找了很久,什么取前几个字节之类来进行判断,都不行,找了好久在网上终于找到一位前辈写的方法,经测试,是完全符合要求的。
package com.mt.qa;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
/**
* <Detect encoding .>
* Copyright (C) <2009> <Fluck,ACC http://androidos.cc/dev>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* EncodingDetect.java<br>
* �Զ���ȡ�ļ��ı���
* @author Billows.Van
* @since Create on 2010-01-27 11:19:00
* @version 1.0
*/
public class EncodingDetect {
public static void main(String[] args) {
String file = "http://s.szmttx.com:81/sp/ds.do?a=&b=1&c=10000&d=1000&e=1&f=13800431500&g=0&h=&i=&j=1&k=46000";
// String file = "D:\\3.txt";
String encode=getJavaEncode(file);
System.out.println(encode);
readFile(file,encode);
}
/**
* �õ��ļ��ı���
* @param filePath �ļ�·��
* @return �ļ��ı���
*/
public static String getJavaEncode(String filePath){
BytesEncodingDetect s = new BytesEncodingDetect();
String fileCode = BytesEncodingDetect.javaname[s.detectEncoding(new File(filePath))];
return fileCode;
}
public static void readFile(String file, String code) {
BufferedReader fr;
try {
String myCode = code!=null&&!"".equals(code) ? code : "UTF8";
InputStreamReader read = new InputStreamReader(new FileInputStream(
file), myCode);
fr = new BufferedReader(read);
String line = null;
int flag=1;
// ��ȡÿһ�У��������ˣ�line��Ϊ��
while ((line = fr.readLine()) != null && line.trim().length() > 0) {
if(flag==1) {
line=line.substring(1);//ȥ���ļ�ͷ
flag++;
}
// ÿһ�д���һ��Student���