过滤上传的txt文件中的BOM

一.现象:

项目中需要上传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方法地方的注释应该酌情去掉。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值