如何使用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);
}}
答案 0 :(得分:3)
嗯,我可以看到三个潜在的问题来源:
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代码点。