测试非 ASCII 字符不起作用 Java

Testing for Non ASCII character not working Java

我有一个包含非 ASCII 字符的文本文件我正在尝试使用 BufferedReader 检测字符在文件中所在的行:

public static void main(String[] args) throws FileNotFoundException, IOException {
        FileInputStream fs = new FileInputStream("C:\Users\Stanley\Documents\file.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fs));
        String line;
        int count = 1;
        while ((line = br.readLine()) != null) {
            if (isAscii(line)) {
                System.out.println(line + " Number " + count);
            }
            count ++;
        }

    }

    public static boolean isAscii(String v) {
        byte bytearray[] = v.getBytes();
        CharsetDecoder d = Charset.forName("US-ASCII").newDecoder();
        try {
            CharBuffer r = d.decode(ByteBuffer.wrap(bytearray));
            r.toString();
        } catch (CharacterCodingException e) {
            return false;
        }
        return true;
    }

我也试过这个检查器,但结果是一样的:

 private static boolean isAsciii(String input) {
        boolean isASCII = true;
        for (int i = 0; i < input.length(); i++) {
            int c = input.charAt(i);
            if (c > 0x7F) {
                isASCII = false;
                break;
            }
        }
        return isASCII;
    }

我的输出是:

我的文本文件如下所示:

我应该如何检查这个。

如果已经有一个字符串,则遍历每个字符并检查每个字符是否在可打印的 ASCII 字符范围内 space (0x20) 到波浪号 (~)。

  public static boolean isAscii(String v) {
      if (s != null && !s.isEmpty()) {
        for(char c : v.toCharArray()) {
            if (c < 0x20 || c > 0x7E) return false;
        }
      }
      return true;  
  }

可能还想回顾一下 Character 静态方法;例如isLetter()、isISOControl() 等。参见 Reference