现在的位置: 首页 > 综合 > 正文

去除java代码中的UTF-8 BOM标识

2018年01月18日 ⁄ 综合 ⁄ 共 585字 ⁄ 字号 评论关闭

我所碰到的情况是:

从txt文件中读取一段字符串,并需要转换成JSONObject,但是由于 txt 的编码是UTF-8 而造成了 BOM 头。所以,用BufferedReader读取InputStream之前,需要对流进行以下处理。


/**

* 读取流中前面的字符,看是否有bom,如果有bom,将bom头先读掉丢弃

* @param in
* @return
* @throws IOException
*/
public static InputStream getInputStream(InputStream in) throws IOException {

PushbackInputStream testin = new PushbackInputStream(in);
int ch = testin.read();
if (ch != 0xEF) {
testin.unread(ch);
} else if ((ch = testin.read()) != 0xBB) {
testin.unread(ch);
testin.unread(0xef);
} else if ((ch = testin.read()) != 0xBF) {
throw new IOException("错误的UTF-8格式文件");
} else {
// 不需要做,这里是bom头被读完了
// // System.out.println("still exist bom");

}
return testin;

}

抱歉!评论已关闭.