代码
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class file {
int line=0;//记录行数
String str="";//存放文件读出的内容
String word;//存放查找的单词
int count;//记录单词出现的次数
public void newFile() throws IOException {
System.out.println("请输入文件地址:");
Scanner scanner=new Scanner(System.in);
String path =scanner.next();
File file = new File(path);
if(!file.exists()){
file.getParentFile().mkdirs();
}
file.createNewFile();
// write
boolean flag=false;
System.out.println("是否输入文本(true/false)");
flag=scanner.nextBoolean();
if(flag==true) {
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("请输入文件内容:");
Scanner s = new Scanner(System.in);
String content = s.nextLine();
bw.write(content);
bw.flush();
bw.close();
fw.close();
}
// read
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
System.out.println("请输入要查询的单词:");
word=scanner.next();
char[]w=word.toCharArray();
while((str=br.readLine())!=null) {
line++;
char[]st=str.toCharArray();
if(KMP(st,w)==true) { //查询单词位置,true表示该单词出现在这一行
System.out.println("在第" + line + "行");
}
}
br.close();
fr.close();
}
//str是待检测字符串,ptr是搜索的模式子串
public boolean KMP(char[] str,char[] ptr){//KMP方法查找单词
//计算模式子串的next数组
int[] next=cal_next(ptr);
boolean flag=false;
int slen=str.length;
int plen=ptr.length;//子串的长度
int num=0;//存放查询单词位置
int j=-1;
for(int i=0;i<slen;i++){
while(j>-1&&ptr[j+1]!=str[i]){
j=next[j];
}
if(ptr[j+1]==str[i]){
j=j+1;
}
if(Character.isSpaceChar(str[i])){
num++;//遇空格单词数位置+1
}
//模式子串遍历到了最后,则说明匹配成功
if(j==(plen-1)){
j=0;
count++;
System.out.println("该单词第"+count+"次"+"出现的位置在第"+(num+1)+"个单词");//存在则输出位置
flag= true;
}
}
return flag;
}
public int[] cal_next(char[] s) {
int len = s.length;
int[] next = new int[len];
next[0] = -1;
int k = -1;//k表示s[0,k]字符串的最长前缀等于最长后缀时的最长前缀长度减去1
//遍历长度为n的子串,时间复杂度O(n)
for (int q = 1; q <= (len - 1); q++) {
//如果下一个不同,那么k就变成next[k],注意next[k]是小于k的,无论k取任何值。
while (k > -1 && s[k + 1] != s[q]) {
k = next[k];//往前回溯
}
if (s[k + 1] == s[q]) {
k = k + 1;
}
//这个是把算的k的值(就是相同的最大前缀或最大后缀的长度减去1)赋给next[q]
next[q] = k;
}
return next;
}
public void start() throws IOException {
newFile();
if(count>0) {
System.out.println("该单词总共出现了" + count + "次");
}else{
System.out.println("该单词在文中不存在!");
}
}
public static void main(String[] args) throws IOException {
file f=new file();
f.start();
}
}
运行结果

文本文件
版权声明:本文为weixin_48122940原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。