首页>代码>java自动根据文件内容的编码来读取避免乱码>/filedetectcharset/src/com/javaniu/test/Main.java
package com.javaniu.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 + "\n";
		}
		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"));
	}
}
最近下载更多
1358849392  LV21 2023年7月4日
神鼎飞丹砂  LV11 2022年4月18日
894529070 2022年1月5日
暂无贡献等级
w73614847  LV6 2021年8月23日
2469095052  LV8 2021年2月2日
aixiao1  LV1 2020年8月7日
hbs2019  LV9 2019年4月23日
oldfox  LV18 2019年3月23日
han891120  LV1 2019年1月29日
WinnieYYY  LV1 2018年12月25日
最近浏览更多
麦瑞邓 2023年3月16日
暂无贡献等级
yiyi2000 2022年12月30日
暂无贡献等级
1358849392  LV21 2022年11月23日
donglixue  LV6 2022年6月8日
神鼎飞丹砂  LV11 2022年4月18日
德莱文  LV15 2022年2月22日
894529070 2022年1月5日
暂无贡献等级
2021年12月1日
暂无贡献等级
融会贯通  LV3 2021年10月12日
lu060606 2021年9月29日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友