在我们对文件进行读、写操作时,经常会涉及到文件的编码格式问题,如果读、写格式不一致或者读的格式或者写的格式与文件本身格式不一致,经常会导致文件乱码,导致读取或者写入操作失败。因此准确的获取文件本身的编码格式就显得非常重要,只有设置了正确的编码格式,才能保证文件的读、写操作不会出错。
目前就一种简单的判断文件编码格式的方法,由于文件的前三个字节往往存放的是编码格式的信息,因此可以通过读取前3个字符来进行判断文件的编码格式,但是这种方式比较繁琐而且很难保证编码格式都能处理到(因为要拿前3个字符与所有可能性字符编码进行比较)。本文提供了一种基于cpdetector获取文件编码格式的方法。
如下代码 请参考:
import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;
import info.monitorenter.cpdetector.io.UnicodeDetector;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
public class test {
/**
* UTF-8 转 EUC-JP
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// 原文件路径
String startPath = "D:\\workspace\\item_data_tool_test\\src";
// 目标路径
String endPath = "D:\\workspace_test\\item_data_tool\\src";
Collection<File> javaGbkFileCol = FileUtils.listFiles(new File(startPath), new String[] { "java" }, true);
for (File javaGbkFile : javaGbkFileCol) {
String endPath2 = endPath + javaGbkFile.getAbsolutePath().substring(startPath.length());
String startPath2 = startPath + javaGbkFile.getAbsolutePath().substring(startPath.length());
String charsetName = getFileEncode(startPath2);
if (!"EUC-JP".equals(charsetName)) {
System.out.println(javaGbkFile.getName() + ":" + charsetName);
FileUtils.writeLines(new File(endPath2), "EUC-JP", FileUtils.readLines(javaGbkFile, charsetName));
}
}
}
public static String getFileEncode(String path) {
CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
detector.add(new ParsingDetector(false));
detector.add(JChardetFacade.getInstance());
detector.add(ASCIIDetector.getInstance());
detector.add(UnicodeDetector.getInstance());
java.nio.charset.Charset charset = null;
File f = new File(path);
try {
charset = detector.detectCodepage(f.toURI().toURL());
} catch (Exception ex) {
ex.printStackTrace();
}
if (charset != null)
return charset.name();
else
return null;
}
}
需要用的jar包
<dependency>
<groupId>cpdetector</groupId>
<artifactId>cpdetector</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>jchardet</groupId>
<artifactId>jchardet</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.2</version>
</dependency>