File file=new File("ABC.txt");
Scanner input=new Scanner(file);
String s=input.toString();
System.out.println(s);
int time=0;
Pattern p = Pattern.compile("abc",Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(s);while(m.find()){
time++;
} System.out.println(time);
}//end main——————————
ABC.txt 中的内容有很多空格和换行
我想检测ABC.txt中制定的单词出现了几次。
为什么time始终为0啊
Scanner input=new Scanner(file);
String s=input.toString();
System.out.println(s);
额,是谁告诉你可以这样输出的. Input.toString()//这里打印不不是txt的内容
至少也应该这样:用循环打印 System.out.println(input.next());
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Test
{
public static void main(String[] args) throws IOException
{
String str = Test.readTxt();
int time=0;
//忽略大写, 换行
Pattern p = Pattern.compile("a",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
Matcher m = p.matcher(str);
while(m.find()){
time++;
}
System.out.println(time);
}
public static String readTxt() throws IOException{
BufferedReader br = new BufferedReader(new FileReader(new File("aa.txt")));
StringBuffer sb = new StringBuffer();
String temp = null;
while((temp = br.readLine()) != null){
sb.append(temp + "\n");
}
return sb.toString();
}
}
小弟对JAVA IO不熟悉
谢谢了