一.现象:
项目中需要上传txt格式的文件进行解析,但不同的文件格式(UTF-8、UTF-8 + BOM、UTF-16, big-endian、UTF-16, little-endian、UTF-32, big-endian、UTF-32, little-endian)会带有不同字节大小的BOM信息导致解析失败。需要将BOM信息过滤掉。google一下,有很多文章,下面是一种解决办法:
二.解决方案:
1.下载java文件
访问:http://koti.mbnet.fi/akini/java/unicodereader/
2.加入到工程中
将
UnicodeInputStream 和 UnicodeReader放到工程中合适的位置(放入后只需要修改包名)
3.客户端调用
private String getContentFromFile(MultipartFile epgFile) throws IOException {
StringBuffer contentBuffer = new StringBuffer();
BufferedReader reader =null;
try {
//去掉UTF+BOM格式中BOM代表的字节
UnicodeInputStream uis = new UnicodeInputStream(epgFile.getInputStream(),"UTF-8");
String actualEncoding = uis.getEncoding();
reader = new BufferedReader(new InputStreamReader(uis,actualEncoding));
String line;
while((line = reader.readLine())!=null){
contentBuffer.append(line).append("\r\n");
}
} catch (IOException e) {
log.error("get content from epg file failed",e);
throw e;
} finally {
try {
if(reader != null){
reader.close();
}
} catch (IOException e) {
log.error("close reader stream failed", e);
throw e;
}
}
return contentBuffer.toString();
}
4.小结
这种方法通过加入UnicodeInputStream,UnicodeInputStream内部通过PushBackInputStream读取文件流中前几个字节并解析是否包含BOM信息,然后调用PushBackInputStream的unread方法将输入流定位到正确的位置(去除BOM信息的第一个字节)来达到去除BOM信息,正确解析文件的目的。
注:UnicodeInputStream和UnicodeReader中调用init方法地方的注释应该酌情去掉。