Java:读取文件时跳过 Unicode 字符

我正在使用以下代码读取文本文件,


try (BufferedReader br = new BufferedReader(new FileReader(<file.txt>))) {

   for (String line; (line = br.readLine()) != null;) {

      //I want to skip a line with unicode character and continue next line

      if(line.toLowerCase().startsWith("\\u")){

            continue;

         //This is not working because i get the character itself and not the text 

        }

    }

}

文本文件:

http://img3.mukewang.com/64141e740001cc1b00470078.jpg

如何在读取文件时跳过所有 unicode 字符?



慕哥6287543
浏览 133回答 3
3回答

炎炎设计

String 中的所有字符都是 Unicode。字符串是 UTF-16 代码单元的计数序列。通过“Unicode”,您必须表示不在某些未指定的其他字符集中。为了争论,让我们说ASCII。正则表达式有时可以是模式要求的最简单表达式:if&nbsp;(!line.matches("\\p{ASCII}*"))&nbsp;continue;也就是说,如果该字符串不只包含任何数字,包括 0,(就是这个意思*)“ASCII”字符,则继续。(String.matches查找整个字符串的匹配项,因此实际的正则表达式模式是^\p{ASCII}*$。)

慕姐4208626

这样的事情可能会让你继续:for (char c : line.toCharArray()) {&nbsp; &nbsp; if (Character.UnicodeBlock.of(c) == Character.UnicodeBlock.BASIC_LATIN) {&nbsp; &nbsp; &nbsp; &nbsp; // do something with this character&nbsp; &nbsp; }}您可以以此为起点来丢弃每个非基本字符,或者丢弃包含单个非基本字符的整行。

冉冉说

您可以跳过所有包含非 ASCII 字符的行:if(Charset.forName("US-ASCII").newEncoder().canEncode(line)){&nbsp; &nbsp;&nbsp;&nbsp;continue;&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java