一、熟悉字符编码:
1、Java中String的默许编码为UTF-8,能够运用以下语句猎取:Charset.defaultCharset();
2、Windows操作系统下,文本文件的默许编码为ANSI,对中文Windows来讲即为GBK。比方我们运用记事本顺序新建一个文本文档,其默许字符编码即为ANSI。
3、Text文本文档有四种编码选项:ANSI、Unicode(含Unicode Big Endian和Unicode Little Endian)、UTF-8、UTF-16
4、因而我们读取txt文件大概有时刻并不知道其编码花样,所以须要用顺序动态推断猎取txt文件编码。
ANSI :无花样定义,对中文操作系统为GBK或GB2312
UTF-8 :前三个字节为:0xE59B9E(UTF-8)、0xEFBBBF(UTF-8含BOM)
UTF-16 :前两字节为:0xFEFF
Unicode:前两个字节为:0xFFFE
比方:Unicode文档以0xFFFE开头,用顺序掏出前几个字节并举行推断即可。
5、Java编码与Text文本编码对应关联:
Java读取Text文件,假如编码花样不婚配,就会涌现乱码征象。所以读取文本文件的时刻须要设置准确字符编码。Text文档编码花样都是写在文件头的,在顺序中须要先剖析文件的编码花样,取得编码花样后,再以此花样读取文件就不会发生乱码了。
免费在线视频教程引荐:java进修
二、举个例子:
有一个文本文件:test.txt
测试代码:
/** * 文件名:CharsetCodeTest.java * 功用形貌:文件字符编码测试 */ import java.io.*; public class CharsetCodeTest { public static void main(String[] args) throws Exception { String filePath = "test.txt"; String content = readTxt(filePath); System.out.println(content); } public static String readTxt(String path) { StringBuilder content = new StringBuilder(""); try { String fileCharsetName = getFileCharsetName(path); System.out.println("文件的编码花样为:"+fileCharsetName); InputStream is = new FileInputStream(path); InputStreamReader isr = new InputStreamReader(is, fileCharsetName); BufferedReader br = new BufferedReader(isr); String str = ""; boolean isFirst = true; while (null != (str = br.readLine())) { if (!isFirst) content.append(System.lineSeparator()); //System.getProperty("line.separator"); else isFirst = false; content.append(str); } br.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("读取文件:" + path + "失利!"); } return content.toString(); } public static String getFileCharsetName(String fileName) throws IOException { InputStream inputStream = new FileInputStream(fileName); byte[] head = new byte[3]; inputStream.read(head); String charsetName = "GBK";//或GB2312,即ANSI if (head[0] == -1 && head[1] == -2 ) //0xFFFE charsetName = "UTF-16"; else if (head[0] == -2 && head[1] == -1 ) //0xFEFF charsetName = "Unicode";//包括两种编码花样:UCS2-Big-Endian和UCS2-Little-Endian else if(head[0]==-27 && head[1]==-101 && head[2] ==-98) charsetName = "UTF-8"; //UTF-8(不含BOM) else if(head[0]==-17 && head[1]==-69 && head[2] ==-65) charsetName = "UTF-8"; //UTF-8-BOM inputStream.close(); //System.out.println(code); return charsetName; } }
运转效果:
相干文章教程引荐:java入门进修
以上就是java完成猎取文本文件的字符编码的细致内容,更多请关注ki4网别的相干文章!