java如何过滤无效的utf-8字符?

之前遇到过几次nutch/solr报这样的错误:Invalid UTF-8 character。 原来1.3版本的nutch有Strip UTF-8 non-character codepoints的bug,在1.4就修复了。

于是这里把nutch里如何过滤无效utf-8字符的代码找出来给小伙伴们看看。直接上代码了:

public static String stripNonCharCodepoints(String input) {
  StringBuilder retval = new StringBuilder();
  char ch;

  for (int i = 0; i < input.length(); i++) {
    ch = input.charAt(i);

    // Strip all non-characters http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[:Noncharacter_Code_Point=True:]
    // and non-printable control characters except tabulator, new line and carriage return
    if (ch % 0x10000 != 0xffff && // 0xffff - 0x10ffff range step 0x10000
        ch % 0x10000 != 0xfffe && // 0xfffe - 0x10fffe range
        (ch <= 0xfdd0 || ch >= 0xfdef) && // 0xfdd0 - 0xfdef
        (ch > 0x1F || ch == 0x9 || ch == 0xa || ch == 0xd)) {

      retval.append(ch);
    }
  }

  return retval.toString();
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值