TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
预先获得文件的编码方式:
- 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) throws Exception{
- DetectingFileCoding DFC=new DetectingFileCoding();
- System.out.println(DFC.codeString("gbkfile.txt"));
- //System.out.println(DFC.getContent("utf-8file.txt"));
- // System.out.println(DFC.getContent("unicodefile.txt"));
- }
- }
- 运行:
- /*
- C:java>java DetectingFileCoding
- UTF-16BE
- C:java>java DetectingFileCoding
- GBK
- */
复制代码
源码下载:http://file.javaxxz.com/2014/11/2/235822406.zip |
|