简要咨询咨询QQ网站导航网站搜索手机站点联系我们设为首页加入收藏 

Java自动根据文件内容的编码来读取避免乱码

来源:易贤网   阅读:1251 次  日期:2015-04-10 16:05:38

温馨提示:易贤网小编为您整理了“Java自动根据文件内容的编码来读取避免乱码”,方便广大网友查阅!

通过cpdetector这个开源的jar包可以自动判断当前文件的内容编码,从而在读取的时候选择正确的编码读取,避免乱码问题。

测试结果,提供截图:

名单

package com.zuidaima.test;

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.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStreamReader;

public class Main {

public static String getContent(String path) throws Exception {

File file = new File(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;

try {

charset = detector.detectCodepage(file.toURI().toURL());

} catch (Exception ex) {

ex.printStackTrace();

}

String charsetName = null;

if (charset != null) {

charsetName = charset.name();

} else {

charsetName = "UTF-8";

}

BufferedReader reader = new BufferedReader(new InputStreamReader(

new FileInputStream(file), charsetName));

String line = null;

String lines = "";

while ((line = reader.readLine()) != null) {

lines += line + " ";

}

reader.close();

return lines;

}

public static void main(String[] args) throws Exception {

System.out.println(getContent("bin/gbk.txt"));

System.out.println(getContent("bin/utf8.txt"));

}

}

更多信息请查看IT技术专栏

更多信息请查看网络编程
点此处就本文及相关问题在本站进行非正式的简要咨询(便捷快速)】     【点此处查询各地各类考试咨询QQ号码及交流群
上一篇:如何做好Flex与Java交互
下一篇:Java中Vector类和Stack类的学习
易贤网手机网站地址:Java自动根据文件内容的编码来读取避免乱码
由于各方面情况的不断调整与变化,易贤网提供的所有考试信息和咨询回复仅供参考,敬请考生以权威部门公布的正式信息和咨询为准!