java如何获取一个文本文件的编码(格式)信息呢?
2023-03-31 10:46:20 时间
转自:http://www.java265.com/JavaJingYan/202110/16350332691561.html
文本文件是我们在windows平台下常用的一种文件格式,
这种格式会随着操作系统的语言不同,而出现其默认的编码不同
那么如何使用程序获取“文本文件”的编码方式呢?
文件编码的格式决定了文件可存储的字符类型,所以得到文件的类型至关重要
下文笔者讲述获取一个文本文件的格式信息的方法分享,如下所示:
实现思路:
通过获取文件流的前3个字节
判断其值的方式,即可获取文本文件的编码方式
例:
package com.java265.other;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Test {
/*
* java265.com 获取文本文件的编码方式
*
**/
public static void main(String[] args) {
File file = new File("E://person/java265.com/java.txt");
System.out.println(GetEncoding(file));
}
public static String GetEncoding(File file)
{
String charset = "GBK";
byte[] first3Bytes = new byte[3];
try {
boolean checked = false;
InputStream is = new FileInputStream(file);
int read = is.read(first3Bytes, 0, 3);
if (read == -1)
return charset;
if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
charset = "UTF-16LE";
checked = true;
} else if (first3Bytes[0] == (byte) 0xFE
&& first3Bytes[1] == (byte) 0xFF) {
charset = "UTF-16BE";
checked = true;
} else if (first3Bytes[0] == (byte) 0xEF
&& first3Bytes[1] == (byte) 0xBB
&& first3Bytes[2] == (byte) 0xBF) {
charset = "UTF-8";
checked = true;
}else if (first3Bytes[0] == (byte) 0xA
&& first3Bytes[1] == (byte) 0x5B
&& first3Bytes[2] == (byte) 0x30) {
charset = "UTF-8";
checked = true;
}else if (first3Bytes[0] == (byte) 0xD
&& first3Bytes[1] == (byte) 0xA
&& first3Bytes[2] == (byte) 0x5B) {
charset = "GBK";
checked = true;
}else if (first3Bytes[0] == (byte) 0x5B
&& first3Bytes[1] == (byte) 0x54
&& first3Bytes[2] == (byte) 0x49) {
charset = "windows-1251";
checked = true;
}
//bis.reset();
InputStream istmp = new FileInputStream(file);
if (!checked) {
int loc = 0;
while ((read = istmp.read()) != -1) {
loc++;
if (read >= 0xF0)
break;
if (0x80 <= read && read <= 0xBF)
break;
if (0xC0 <= read && read <= 0xDF) {
read = istmp.read();
if (0x80 <= read && read <= 0xBF)
continue;
else
break;
} else if (0xE0 <= read && read <= 0xEF) {
read = istmp.read();
if (0x80 <= read && read <= 0xBF) {
read = istmp.read();
if (0x80 <= read && read <= 0xBF) {
charset = "UTF-8";
break;
} else
break;
} else
break;
}
}
}
is.close();
istmp.close();
} catch (Exception e) {
e.printStackTrace();
}
return charset;
}
}
相关文章
- Java程序员这项技能没掌握,还是别去面试了
- 频繁插入(insert)的业务,用什么存储引擎更合适? | 数据库系列
- Java大牛分享关于Redis缓存的几道典型面试题
- Java架构之Redis系列:通过文章点赞排名案例学习Sortedset命令
- 基于内存和 Redis 的两级 Java 缓存框架
- Java 框架之Redis 分布式缓存
- Java开发人员使用哪些大数据工具?
- 聊聊Java数据库开发的那点事儿
- 是否值得付费?Oracle,Open JDK等四大JVM性能全面对比
- 主流Java数据库连接池分析(C3P0,DBCP,TomcatPool,BoneCP,Druid)
- Java面试中常问的数据库方面问题
- Java高级编程——慢SQL问题经验总结
- Java面试要点-数据存储-精简答案
- 使用Java语言从零开始创建区块链
- 基于OS信号实现Java异步通知
- 在Android Native层中创建Java虚拟机实例
- Java Memcached Client Benchmark
- Practical Clojure - Parallel Programming
- Storm源码浅析之topology的提交
- 春节值班智能通知