【问题标题】:search a unicode string in a file using java使用java搜索文件中的unicode字符串
【发布时间】:2011-12-18 03:09:38
【问题描述】:

如何使用 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);
   }}

【问题讨论】:

    标签: java string file search unicode


    【解决方案1】:

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

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

    为了调试字符串中的 real 值,我通常会使用这样的东西:

    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 代码点。

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 1970-01-01
      • 2015-09-24
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 2015-11-02
      • 1970-01-01
      • 2017-01-24
      相关资源
      最近更新 更多