码迷,mamicode.com
首页 > 其他好文 > 详细

常用技术汇总

时间:2016-11-03 02:18:56      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:char   return   trace   print   fileinput   dia   string   font   bsp   

一、获取文件的编码格式

当我们在使用文件输入输出流时,经常会出现乱码问题,这通常是由于编码格式导致的。

以复制一份文件为例:

我们用输入流(FileInputStream)读取文件,然后用输出流(FileOutPutStream)重新写入到另一个文件,

如果源文件的编码格式和我们重新写入时的编码格式不一致,那么就可能出现乱码问题。

因此,我们需要获取源文件的编码格式,以便在重新写入时使用相同的编码格式。

 

下面介绍一个简单的方式准确获取文件的编码格式:

一般地,我们根据文件的前三个字节就可以判断该文件是什么编码格式,如下:

EF BB BF    UTF-8  
FE FF      UTF-16/UCS-2, little endian  
FF FE      UTF-16/UCS-2, big endian  
FF FE 00 00  UTF-32/UCS-4, little endian.  
00 00 FE FF  UTF-32/UCS-4, big-endian.

因此,我么读取文件的前几个字节就可用于判断文件的编码格式,代码如下:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

public class GetFileEncode {
public static void main(String[] args) {
String filePath = "D:\\javaTest\\test.txt";
File sourceFile = new File(filePath);
getFilecharset(sourceFile);
}

private static String getFilecharset(File sourceFile) {
String charset = "GBK";
byte[] first3Bytes = new byte[3];
try {
boolean checked = false;
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
bis.mark(0);
int read = bis.read(first3Bytes, 0, 3);
if (read == -1) {
return charset; // 文件编码为 ANSI
} else if (first3Bytes[0] == (byte) 0xFF
&& first3Bytes[1] == (byte) 0xFE) {
charset = "UTF-16LE"; // 文件编码为 Unicode
checked = true;
} else if (first3Bytes[0] == (byte) 0xFE
&& first3Bytes[1] == (byte) 0xFF) {
charset = "UTF-16BE"; // 文件编码为 Unicode big endian
checked = true;
} else if (first3Bytes[0] == (byte) 0xEF
&& first3Bytes[1] == (byte) 0xBB
&& first3Bytes[2] == (byte) 0xBF) {
charset = "UTF-8"; // 文件编码为 UTF-8
checked = true;
}
bis.reset();
if (!checked) {
int loc = 0;
while ((read = bis.read()) != -1) {
loc++;
if (read >= 0xF0)
break;
if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK
break;
if (0xC0 <= read && read <= 0xDF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)
// (0x80
// - 0xBF),也可能在GB编码内
continue;
else
break;
} else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
charset = "UTF-8";
break;
} else
break;
} else
break;
}
}
}
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.print(charset);
return charset;
}
}

 

常用技术汇总

标签:char   return   trace   print   fileinput   dia   string   font   bsp   

原文地址:http://www.cnblogs.com/FZ1314/p/6024852.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!