Java读取UTF-8格式txt文件第一行出现乱码及解决;Java读带有BOM的UTF-8文件乱码原因及解决方法(转载)
原文地址:http://blog.csdn.net/jackpk/article/details/5702964/
Java读取UTF-8的txt文件第一行出现乱码“?”及解决
test.txt文件内容:
A中
2国
3
4
5
6
test.txt文件采用写字板保存为UTF-8格式
保存并关闭后使用写字板再次打开该UTF-8文档,中文、字母正常显示
测试代码:
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStreamReader;
- public class ReadTxtFile {
- public static void main(String[] args) {
- try {
- String charsetName = "UTF-8";
- String path = "D:/to_delete/test.txt";
- File file = new File(path);
- if (file.isFile() && file.exists())
- {
- InputStreamReader insReader = new InputStreamReader(
- new FileInputStream(file), charsetName);
- BufferedReader bufReader = new BufferedReader(insReader);
- String line = new String();
- while ((line = bufReader.readLine()) != null) {
- System.out.println(line);
- }
- bufReader.close();
- insReader.close();
- }
- } catch (Exception e) {
- System.out.println("读取文件内容操作出错");
- e.printStackTrace();
- }
- }
- }
程序执行结果:
?A中
2国
3
4
5
6
我的解决办法:
使用UltraEdit将上边的txt文件另存为UTF-8无BOM格式;
或者
使用Notepad++打开上边的txt文件执行如下操作“格式-->以UTF-8无BOM格式编码”,修改后将txt文本进行保存。
网上有篇非常好的文章,论述了问题出现的原因及解决办法
Java读带有BOM的UTF-8文件乱码原因及解决方法
url:http://daimojingdeyu.javaeye.com/blog/397661
关键字: java 读utf-8, java写utf-8, 编码, utf-8 乱码
上网找了一下,找到几篇比较好文章,这里就不转载啦把链接搞过来。
文件编码问题集锦
字符串编码(charset,encoding,decoding)问题原理
Java编码浅析
判定文件编码或文本流编码的方法
上面的几篇文章可以看成认识编码问题的“从入门到精通”
如果你看完了上面的文章,一定了解到了,在java中,class文件采用utf8的编码方式,JVM运行时采用utf16。Java的字符串是永远都是unicode的,采用的是UTF-16的编码方式。
想测试一下,java对UTF-8文件的读写的能力,结果发现了一个很郁闷的问题,如果通过java写的UTF-8文件,使用Java可以正确的读,但是如果用记事本将相同的内容使用UTF-8格式保存,则在使用程序读取是会从文件中多读出一个不可见字符。
测试代码如下:
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class UTF8Test {
- public static void main(String[] args) throws IOException {
- File f = new File("./utf.txt");
- FileInputStream in = new FileInputStream(f);
- // 指定读取文件时以UTF-8的格式读取
- BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
- String line = br.readLine();
- while(line != null)
- {
- System.out.println(line);
- line = br.readLine();
- }
- }
- }
This is the first line.
This is second line.
正常的测试结果应该是直接输出utf.txt的文本内容。可是实际上却输出了下面的内容:
?This is the first line.
This is second line.
第一行多出了一个问号。
通过上面的几篇文章应该可以想到是Java读取BOM(Byte Order Mark)的问题,在使用UTF-8时,可以在文件的开始使用3个字节的"EF BB BF"来标识文件使用了UTF-8的编码,当然也可以不用这个3个字节。
上面的问题应该就是因为对开头3个字节的读取导致的。开始不太相信这个是JDK的Bug,后来在多次试验后,问题依然存在,就又狗狗了一下,果然找到一个如下的Bug:
Bug ID:4508058
不过在我关掉的一些页面中记得有篇文件说这个bug只在jdk1.5及之前的版本才有,说是1.6已经解决了,从目前来看1.6只是解决了读取带有BOM文件失败的问题,还是不能区别处理有BOM和无BOM的UTF-8编码的文件,从Bug ID:4508058里的描述可以看出,这个问题将作为一个不会修改的问题关闭,对于BOM编码的识别将由应用程序自己来处理,原因可从另处一个bug处查看到,因为Unicode对于BOM的编码的规定可能发生变化。也就是说对于一个UTF-8的文件,应用程序需要知道这个文件有没有写BOM,然后自己决定处理BOM的方式。
在上面的while循环中可加入下面的代码,测试一下读出内容:
- byte[] allbytes = line.getBytes("UTF-8");
- for (int i=0; i < allbytes.length; i++)
- {
- int tmp = allbytes[i];
- String hexString = Integer.toHexString(tmp);
- // 1个byte变成16进制的,只需要2位就可以表示了,取后面两位,去掉前面的符号填充
- hexString = hexString.substring(hexString.length() -2);
- System.out.print(hexString.toUpperCase());
- System.out.print(" ");
- }
EF BB BF 54 68 69 73 20 69 73 20 74 68 65 20 66 69 72 73 74 20 6C 69 6E 65 2E
?This is the first line.
54 68 69 73 20 69 73 20 73 65 63 6F 6E 64 20 6C 69 6E 65 2E
This is second line.
红色部分的"EF BB BF"刚好是UTF-8文件的BOM编码,可以看出Java在读文件时没能正确处理UTF-8文件的BOM编码,将前3个字节当作文本内容来处理了。
使用链接中提供的代码可以解决碰到的乱码问题:
http://koti.mbnet.fi/akini/java/unicodereader/
修改测试代码中的输入流后:
- BufferedReader br = new BufferedReader(new UnicodeReader(in, Charset.defaultCharset().name()));
将用到的测试代码及UTF-8读取乱码解决(http://koti.mbnet.fi/akini/java/unicodereader)的源码放在了附件中
压缩包中的源代码
UnicodeInputStream.java
- /**
- version: 1.1 / 2007-01-25
- - changed BOM recognition ordering (longer boms first)
- Original pseudocode : Thomas Weidenfeller
- Implementation tweaked: Aki Nieminen
- http://www.unicode.org/unicode/faq/utf_bom.html
- BOMs in byte length ordering:
- 00 00 FE FF = UTF-32, big-endian
- FF FE 00 00 = UTF-32, little-endian
- EF BB BF = UTF-8,
- FE FF = UTF-16, big-endian
- FF FE = UTF-16, little-endian
- Win2k Notepad:
- Unicode format = UTF-16LE
- ***/
- import java.io.*;
- /**
- * This inputstream will recognize unicode BOM marks and will skip bytes if
- * getEncoding() method is called before any of the read(...) methods.
- *
- * Usage pattern: String enc = "ISO-8859-1"; // or NULL to use systemdefault
- * FileInputStream fis = new FileInputStream(file); UnicodeInputStream uin = new
- * UnicodeInputStream(fis, enc); enc = uin.getEncoding(); // check and skip
- * possible BOM bytes InputStreamReader in; if (enc == null) in = new
- * InputStreamReader(uin); else in = new InputStreamReader(uin, enc);
- */
- public class UnicodeInputStream extends InputStream {
- PushbackInputStream internalIn;
- boolean isInited = false;
- String defaultEnc;
- String encoding;
- private static final int BOM_SIZE = 4;
- UnicodeInputStream(InputStream in, String defaultEnc) {
- internalIn = new PushbackInputStream(in, BOM_SIZE);
- this.defaultEnc = defaultEnc;
- }
- public String getDefaultEncoding() {
- return defaultEnc;
- }
- public String getEncoding() {
- if (!isInited) {
- try {
- init();
- } catch (IOException ex) {
- IllegalStateException ise = new IllegalStateException(
- "Init method failed.");
- ise.initCause(ise);
- throw ise;
- }
- }
- return encoding;
- }
- /**
- * Read-ahead four bytes and check for BOM marks. Extra bytes are unread
- * back to the stream, only BOM bytes are skipped.
- */
- protected void init() throws IOException {
- if (isInited)
- return;
- byte bom[] = new byte[BOM_SIZE];
- int n, unread;
- n = internalIn.read(bom, 0, bom.length);
- if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00)
- && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
- encoding = "UTF-32BE";
- unread = n - 4;
- } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)
- && (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) {
- encoding = "UTF-32LE";
- unread = n - 4;
- } else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB)
- && (bom[2] == (byte) 0xBF)) {
- encoding = "UTF-8";
- unread = n - 3;
- } else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
- encoding = "UTF-16BE";
- unread = n - 2;
- } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
- encoding = "UTF-16LE";
- unread = n - 2;
- } else {
- // Unicode BOM mark not found, unread all bytes
- encoding = defaultEnc;
- unread = n;
- }
- // System.out.println("read=" + n + ", unread=" + unread);
- if (unread > 0)
- internalIn.unread(bom, (n - unread), unread);
- isInited = true;
- }
- public void close() throws IOException {
- // init();
- isInited = true;
- internalIn.close();
- }
- public int read() throws IOException {
- // init();
- isInited = true;
- return internalIn.read();
- }
- }
UnicodeReader.java
- /**
- version: 1.1 / 2007-01-25
- - changed BOM recognition ordering (longer boms first)
- Original pseudocode : Thomas Weidenfeller
- Implementation tweaked: Aki Nieminen
- http://www.unicode.org/unicode/faq/utf_bom.html
- BOMs:
- 00 00 FE FF = UTF-32, big-endian
- FF FE 00 00 = UTF-32, little-endian
- EF BB BF = UTF-8,
- FE FF = UTF-16, big-endian
- FF FE = UTF-16, little-endian
- Win2k Notepad:
- Unicode format = UTF-16LE
- ***/
- import java.io.*;
- /**
- * Generic unicode textreader, which will use BOM mark to identify the encoding
- * to be used. If BOM is not found then use a given default or system encoding.
- */
- public class UnicodeReader extends Reader {
- PushbackInputStream internalIn;
- InputStreamReader internalIn2 = null;
- String defaultEnc;
- private static final int BOM_SIZE = 4;
- /**
- *
- * @param in
- * inputstream to be read
- * @param defaultEnc
- * default encoding if stream does not have BOM marker. Give NULL
- * to use system-level default.
- */
- UnicodeReader(InputStream in, String defaultEnc) {
- internalIn = new PushbackInputStream(in, BOM_SIZE);
- this.defaultEnc = defaultEnc;
- }
- public String getDefaultEncoding() {
- return defaultEnc;
- }
- /**
- * Get stream encoding or NULL if stream is uninitialized. Call init() or
- * read() method to initialize it.
- */
- public String getEncoding() {
- if (internalIn2 == null)
- return null;
- return internalIn2.getEncoding();
- }
- /**
- * Read-ahead four bytes and check for BOM marks. Extra bytes are unread
- * back to the stream, only BOM bytes are skipped.
- */
- protected void init() throws IOException {
- if (internalIn2 != null)
- return;
- String encoding;
- byte bom[] = new byte[BOM_SIZE];
- int n, unread;
- n = internalIn.read(bom, 0, bom.length);
- if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00)
- && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
- encoding = "UTF-32BE";
- unread = n - 4;
- } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)
- && (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) {
- encoding = "UTF-32LE";
- unread = n - 4;
- } else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB)
- && (bom[2] == (byte) 0xBF)) {
- encoding = "UTF-8";
- unread = n - 3;
- } else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
- encoding = "UTF-16BE";
- unread = n - 2;
- } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
- encoding = "UTF-16LE";
- unread = n - 2;
- } else {
- // Unicode BOM mark not found, unread all bytes
- encoding = defaultEnc;
- unread = n;
- }
- // System.out.println("read=" + n + ", unread=" + unread);
- if (unread > 0)
- internalIn.unread(bom, (n - unread), unread);
- // Use given encoding
- if (encoding == null) {
- internalIn2 = new InputStreamReader(internalIn);
- } else {
- internalIn2 = new InputStreamReader(internalIn, encoding);
- }
- }
- public void close() throws IOException {
- init();
- internalIn2.close();
- }
- public int read(char[] cbuf, int off, int len) throws IOException {
- init();
- return internalIn2.read(cbuf, off, len);
- }
- }
UTF8Test.java
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.nio.charset.Charset;
- public class UTF8Test {
- public static void main(String[] args) throws IOException {
- File f = new File("./utf.txt");
- FileInputStream in = new FileInputStream(f);
- // 指定读取文件时以UTF-8的格式读取
- // BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
- BufferedReader br = new BufferedReader(new UnicodeReader(in, Charset.defaultCharset().name()));
- String line = br.readLine();
- while(line != null)
- {
- System.out.println(line);
- line = br.readLine();
- }
- }
- }
第二篇文章:
Java读取utf-8文件注意有无BOM
原文地址:http://53873039oycg.iteye.com/blog/2030463
各位看标题就知道我要写什么了,先写结论,读取utf-8格式的文件时候,注意文件开头可能含有BOM标识符,结论写完了,下面的没必要看了,我记录下问题解决方法而已。
虽然早知道utf-8文件可能含有bom标识符,我一直没碰到过,知道今天,我测试时候发现字符串长度不对劲,如下所示:
长度不对劲,我就开始怀疑我碰上了传说中的BOM标识符了,下面可是验证,上代码:
- public class UTFBOM文件处理 {
- public static void main(String[] args) throws Exception {
- List<String> resultList = readFileByLine("f:/saveFile/temp/name2.txt");
- String tmpStr = resultList.get(0);
- System.out.println(tmpStr + "----len=" + tmpStr.length());
- String tmpStr2 = new String(tmpStr.substring(0, 1));
- System.out.println(tmpStr2 + "----hex=" + strtoHex(tmpStr2));
- }
- public static String strtoHex(String s) {
- String str = "";
- for (int i = 0; i < s.length(); i++) {
- int ch = (int) s.charAt(i);
- String s4 = Integer.toHexString(ch);
- str = str + s4;
- }
- return "0x" + str;// 0x表示十六进制
- }
- public static List<String> readFileByLine(String filename) throws Exception {
- List<String> nameList = new ArrayList<String>();
- File file = new File(filename);
- InputStreamReader isr = new InputStreamReader(
- new FileInputStream(file), "UTF-8");
- BufferedReader reader = new BufferedReader(isr);
- String tmp = reader.readLine();
- while (tmp != null && tmp.trim().length() > 0) {
- nameList.add(tmp);
- tmp = reader.readLine();
- }
- reader.close();
- return nameList;
- }
- }
结果为:
- 掬水月在手----len=6
- ----hex=0xfeff
看到好熟悉的feff。
使用16进制打开文件,可以看到BOM标识符了。
BOM是什么,可以参考链接:
http://mindprod.com/jgloss/bom.html
ef bb bf
解决方法:
http://koti.mbnet.fi/akini/java/unicodereader/
- public static List<String> readFileByLineWithOutBom(String filename)
- throws Exception {
- List<String> nameList = new ArrayList<String>();
- File file = new File(filename);
- InputStream in = new FileInputStream(file);
- BufferedReader reader = new BufferedReader(new UnicodeReader(in,
- "utf-8"));
- String tmp = reader.readLine();
- while (tmp != null && tmp.trim().length() > 0) {
- nameList.add(tmp);
- tmp = reader.readLine();
- }
- reader.close();
- return nameList;
- }
带BOM标识符的文件怎么产生的呢?
系统默认另存为utf-8保存的就是带bom的,以前一直用nodepad++另存为的,今天犯二了,忘了。
全文完。