Java自动检测文件编码(字符集)

本文介绍了一种使用IBM ICU4J库检测文件编码并读取的方法,通过CharsetDetector类可以自动识别文件的字符集,如gb18030、big5、utf-8等,确保文件内容正确读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


// 使用之前请调用getAllDetectableCharsets()检查是否满足要求,中文仅有{gb18030, big5,utf-*}
import
com.ibm.icu.text.CharsetDetector; import com.ibm.icu.text.CharsetMatch; static HashSet<String> getWhiteList(String fileName) { if (fileName == null) { return null; } HashSet<String> rs = null; InputStreamReader isr = null; BufferedReader br = null; try { FileInputStream fis = new FileInputStream(fileName); BufferedInputStream bis = new BufferedInputStream(fis);// markSupported CharsetMatch charsetMatch = new CharsetDetector().setText(bis).detect(); if (charsetMatch != null) { isr = new InputStreamReader(bis, charsetMatch.getName()); System.out.println("Open '" + fileName + " ' with charset: " + charsetMatch.getName()); } else { isr = new InputStreamReader(bis); System.out.println( "Open '" + fileName + " ' with charset( default, because no charset is detected by IBM.ICU4J): " + isr.getEncoding()); } br = new BufferedReader(isr); String line = null; rs = new HashSet<String>(); while ((line = br.readLine()) != null) { rs.add(line); } } catch (FileNotFoundException e) { System.out.println("WARNING: File '" + fileName + "' is not exist."); } catch (IOException e) { System.out.println("WARNING: IOException occured when read Whitelist."); } finally { try { if (br != null) { br.close(); } } catch (IOException e) { System.out.println("WARNING: IOException occured when close BufferedReader."); } } return rs; }

 

转载于:https://www.cnblogs.com/chenhuanBlogs/p/10229413.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值