使用java搜索文件中的unicode字符串
如何使用java搜索文件中的unicode字符串? 下面是我尝试过的代码。它可以处理unicode以外的字符串使用java搜索文件中的unicode字符串,java,string,file,search,unicode,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 Excepti
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);
}}
嗯,我可以看到三个潜在的问题来源:
- 正则表达式可能不正确。你真的需要使用正则表达式吗?您是在尝试匹配一个模式,还是只是一个简单的字符串
- 您可能无法从命令行获取非ASCII输入。您应该根据输入字符串的Unicode字符转储输入字符串(请参见后面的代码)
- 您很可能正在以错误的编码读取文件。当前您使用的是
,它始终使用平台默认编码。您试图读取的文件的编码是什么?我建议使用FileReader
包装在FileInputStream
中,使用与文件匹配的显式编码(例如UTF-8)InputStreamReader
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();
}
}
私有静态无效转储字符串(字符串文本){
对于(int i=0;i
这样,您可以在字符串中的每个char
中看到确切的UTF-16代码点