java判断文本文件编码格式
上篇文章需要读取当前java或者配置文件的编码格式,这里主要支持UTF-8、GBK、UTF-16、Unicode等
/**
* 判断文件的编码格式
* @param fileName :file
* @return 文件编码格式
* @throws Exception
*/
public static String codeString(File fileName) throws Exception{
BufferedInputStream bin = new BufferedInputStream(
new FileInputStream(fileName));
int p = (bin.read() << 8) + bin.read();
String code = null;
switch (p) {
case 0xefbb:
code = "UTF-8";
break;
case 0xfffe:
code = "Unicode";
break;
case 0xfeff:
code = "UTF-16BE";
break;
default:
code = "GBK";
}
IOUtils.closeQuietly(bin);
return code;
}
上面这段代码只能判断带bom的文本,如果非bom文本,还有两种方式
1、 轮询常用的编码,知道找到匹配的,如下面一段测试代码
/*
* Copyright 2010 Georgios Migdos <cyberpython@gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* under the License.
*/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
/**
*
* @author Georgios Migdos <cyberpython@gmail.com>
*/
public class CharsetDetector {
public Charset detectCharset(File f, String[] charsets) {
Charset charset = null;
for (String charsetName : charsets) {
charset = detectCharset(f, Charset.forName(charsetName));
if (charset != null) {
break;
}
}
return charset;
}
private Charset detectCharset(File f, Charset charset) {
try {
BufferedInputStream input = new BufferedInputStream(new FileInputStream(f));
CharsetDecoder decoder = charset.newDecoder();
decoder.reset();
byte[] buffer = new byte[512];
boolean identified = false;
while ((input.read(buffer) != -1) && (!identified)) {
identified = identify(buffer, decoder);
}
input.close();
if (identified) {
return charset;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
private boolean identify(byte[] bytes, CharsetDecoder decoder) {
try {
decoder.decode(ByteBuffer.wrap(bytes));
} catch (CharacterCodingException e) {
return false;
}
return true;
}
public static void main(String[] args) {
File f = new File("example.txt");
String[] charsetsToBeTested = {"UTF-8", "windows-1253", "ISO-8859-7"};
CharsetDetector cd = new CharsetDetector();
Charset charset = cd.detectCharset(f, charsetsToBeTested);
if (charset != null) {
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(f), charset);
int c = 0;
while ((c = reader.read()) != -1) {
System.out.print((char)c);
}
reader.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}else{
System.out.println("Unrecognized charset.");
}
}
}
2、 使用谷歌依赖库来进行判断
https://code.google.com/archive/p/juniversalchardet/
java判断文本文件编码格式的更多相关文章
- Java判断文件编码格式
转自:http://blog.csdn.net/zhangzh332/article/details/6719025 一般情况下我们遇到的文件编码格式为GBK或者UTF-8.由于中文Windows默认 ...
- Java推断文本文件编码格式以及读取
假设不是约定好的,要想解析txt文件就须要知道文件编码类型,因为文件编码类型众多.比如UTF-8,GBK.UTF-16,GB2312等等. 事实上有简单的办法.仅仅须要这样就能够了 String fi ...
- (转) Java读取文本文件中文乱码问题
http://blog.csdn.net/greenqingqingws/article/details/7395213 最近遇到一个问题,Java读取文本文件(例如csv文件.txt文件等),遇到中 ...
- Java读取文本文件中文乱码问题 .转载
最近遇到一个问题,Java读取文本文件(例如csv文件.txt文件等),遇到中文就变成乱码.读取代码如下: List<String> lines=new ArrayList<Stri ...
- Eclipse: eclipse文本文件编码格式更改(GBK——UTF-8)
Eclipse中设置编码的方式 Eclipse工 作空间(workspace)的缺省字符编码是操作系统缺省的编码,简体中文操作系统 (Windows XP.Windows 2000简体中文)的缺省编码 ...
- Java读取文本文件中文乱码问题
最近遇到一个问题,Java读取文本文件(例如csv文件.txt文件等),遇到中文就变成乱码.读取代码如下: List<String> lines=new ArrayList<Stri ...
- Java读写文本文件操作
package com.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; ...
- 使用Java判断字符串中的中文字符数量
Java判断一个字符串str中中文的个数,经过总结,有以下几种方法(全部经过验证),可根据其原理判断在何种情况下使用哪个方法: 1. char[] c = str.toCharArray(); for ...
- Java判断回文数算法简单实现
好久没写java的代码了, 今天闲来无事写段java的代码,算是为新的一年磨磨刀,开个头,算法是Java判断回文数算法简单实现,基本思想是利用字符串对应位置比较,如果所有可能位置都满足要求,则输入的是 ...
- Java 判断操作系统类型(适用于各种操作系统)
Java 判断操作系统类型(适用于各种操作系统) 最近一段时间写一个授权的程序,需要获取很多信息来保证程序不能随意复制使用,必须经过授权才可以. 为了限制用户使用的操作系统,必须有统一的方法来获取才可 ...
随机推荐
- .NET Core MVC基础之返回文件类型
.NET Core MVC基础之返回文件类型 前言 上一篇文章讲了基础的返回类型,这篇文章讲解如何返回文件类型给浏览器下载. 系列文章 .NET MVC基础之页面传值方式 通过图片流来返回图片 返回类 ...
- STM32 CubeMX 学习:004-PWM
背景 上一讲,我们介绍了 STM32 CubeMX 学习:定时器 ,并示范了如何使用定时器来定时.这一讲我们来试试PWM(Pulse Width Modulation, 脉冲宽度调制),这是利用微处理 ...
- 使用Github Action来辅助项目管理
Github action 是一个Github官方提供的非常流行且速度集成 持续集成和持续交付(CI/CD)的工具.它允许你在GitHub仓库中自动化.定制和执行你的软件开发工作流.你可以发现.创建和 ...
- bash shell基础命令
bash shell基础命令 很多Linux发行版的默认shell是GNU bash shell. 1. 启动shell GNU bash shell是一个程序,提供了对Linux系统的交互式访问.它 ...
- ubuntu22 flask项目 pyinstaller打包后运行报错: jinja2.exceptions.TemplateNotFound: index.html 的一种解决方案
前言 有一个flask项目a.py, 目录结构如下: |- a.py |- templates | - index.html |- static |- images 运行 python3 a.py可以 ...
- UWP WinUI 制作一个路径矢量图标按钮样式入门
本文将告诉大家如何在 UWP 或 WinUI3 或 UNO 里,如何制作一个路径按钮.路径按钮就是使用几何路径轮廓表示内容的按钮,常见于各种图标按钮,或 svg 系贴图矢量图按钮 在网上有非常多矢量图 ...
- 谈谈你对MVVM开发模式和MVT的理解?
MVVM分为Model.View.ViewModel三者. Model 代表数据模型,数据和业务逻辑都在Model层中定义: View 代表UI视图,负责数据的展示: ViewModel 负责监听 M ...
- VUEX - 手稿
- Vue源码学习(二十):$emit、$on实现原理
好家伙, 0.一个例子 <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset= ...
- SafeLine Web 安全网关保护你的网站不受黑客攻击
SafeLine 简介 今天,推荐给大家的是一款在社区广受好评的网站防护工具 -- SafeLine Web 安全网关. 简单来说这是一个自带安全 buf 的 Nginx,它基于业界领先的语义分析检测 ...