-
大小: 159KB文件类型: .java金币: 1下载: 0 次发布日期: 2021-05-13
- 语言: Java
- 标签:
资源简介
当我们循环遍历文件进行操作的时候可能遇到各种各样的文件编码格式,如果不知道当前循环的文件格式的话,将会遇到各种各样的问题,因此这个工具类就应运而生了!使用java动态识别文件编码EncodingDetect.java这个工具类以后就变得异常简单了!
代码片段和文件信息
package com.sjfl.main;
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;
/**
*
* Copyright (C) <2009>
*
* 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
* 自动获取文件的编码
* 使用示例
String filePath=“D:/test.txt“;
//获得文件编码
String fileEncode=EncodingDetect.getJavaEncode(filePath);
//根据文件编码获得文件内容
String fileContent=FileUtils.readFileToString(new File(filePath)fileEncode)
* @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 = “E:/PWCP_ANM_ARQC_S99_EAIR_ANM_L88_P9_20100126150002424.xml“;
String encode=getJavaEncode(file);
System.out.println(encode);
readFile(fileencode);
}
/**
* 得到文件的编码
* @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对象,并存入数组中
System.out.println(line);
}
fr.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class BytesEncodingDetect extends Encoding {
// Frequency tables to hold the GB Big5 and EUC-TW character
// frequencies
int GBFreq[][];
int GBKFreq[][];
int Big5Freq[][];
int Big5PFreq[][];
int EUC_TWFreq[][];
int KRFreq[][];
int JPFreq[][];
// int UnicodeFreq[94][128];
// public static String[] nicename;
// public static Strin
- 上一篇:五子棋 人机对弈 JAVA实现
- 下一篇:POI读取Excel合并单元格并储存
评论
共有 条评论