使用java搜索文件中的unicode字符串

时间:2011-10-30 07:35:32

标签: java string file search unicode

如何使用java搜索文件中的unicode字符串? 下面是我尝试过的代码。它的工作方式不是unicode。

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    import java.util.*;
    class file1
    {
   public static void main(String arg[])throws Exception
   {
    BufferedReader bfr1 = new BufferedReader(new InputStreamReader(
            System.in));
    System.out.println("Enter File name:");
    String str = bfr1.readLine();
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String s;
    int count=0;
    int flag=0;

    System.out.println("Enter the string to be found");
    s=br.readLine();
    BufferedReader bfr = new BufferedReader(new FileReader(str));
    String bfr2=bfr.readLine();
    Pattern p = Pattern.compile(s);
            Matcher matcher = p.matcher(bfr2);
            while (matcher.find()) {
            count++;
            }System.out.println(count);
   }}

1 个答案:

答案 0 :(得分:3)

嗯,我可以看到三个潜在的问题来源:

  • 正则表达式可能不正确。你真的需要使用正则表达式吗?你想要匹配一个模式,还是只是一个简单的字符串?
  • 您可能无法从命令行获取非ASCII输入。您应该根据其Unicode字符转储输入字符串(请参阅后面的代码)。
  • 您可能正在使用错误的编码读取文件。目前您正在使用始终使用平台默认编码的FileReader。您尝试阅读的文件的编码是什么?我建议使用与FileInputStream包装的InputStreamReader,使用与文件匹配的显式编码(例如UTF-8)。

要调试字符串中的真实值,我通常会使用以下内容:

private static void dumpString(String text) {
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        System.out.printf("%d: %4h (%c)", i, c, c);
        System.out.println();
    }
}

通过这种方式,您可以在字符串中的每个char中看到确切的UTF-16代码点。