package com.test.newfile.Controller;
import java.io.*;
import java.util.Scanner;
/**
* @ClassName TextFileSearch
* @Author :zhaofuh
* @Date :2021/3/15 10:57
* @Description:
* @Version: 1.0
*/
public class TextFileSearch {
public void SearchKeyword(File file,String keyword) {
//参数校验
verifyParam(file, keyword);
//行读取
LineNumberReader lineReader = null;
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "GB2312");
BufferedReader br = new BufferedReader(isr);
String readLine;
int id=-1;
while((readLine =br.readLine()) != null){
//判断每一行中,出现关键词的次数
int index = 0;
int next = 0;
id++;
// System.out.println(readLine);
if((index = readLine.indexOf(keyword,next)) != -1) {
next = index + keyword.length();
System.out.println("关键字"+keyword+"的字段id为:"+id);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
close(lineReader);
}
}
/**
*
* 功能描述:
*
* @param:
* @return:
* @author: zhaofuh
* @date: 2021/3/15 11:39
*/
private void verifyParam(File file, String keyword) {
//对参数进行校验证
if(file == null ){
throw new NullPointerException("the file is null");
}
if(keyword == null || keyword.trim().equals("")){
throw new NullPointerException("the keyword is null or \"\" ");
}
if(!file.exists()) {
throw new RuntimeException("the file is not exists");
}
//非目录
if(file.isDirectory()){
throw new RuntimeException("the file is a directory,not a file");
}
//可读取
if(!file.canRead()) {
throw new RuntimeException("the file can't read");
}
}
/**
*
* 功能描述:
*
* @param:
* @return:
* @author: zhaofuh
* @date: 2021/3/15 11:38
*/
private void close(Closeable able){
if(able != null){
try {
able.close();
} catch (IOException e) {
e.printStackTrace();
able = null;
}
}
}
public static void main(String[] args) {
TextFileSearch search = new TextFileSearch();
while (true) {
System.out.println("请输入字段:");
Scanner in = new Scanner(System.in);
String input = in.next();
search.SearchKeyword(new File("C:\\Users\\admin\\Desktop\\char_std_5990.txt"), input);
if (input.equalsIgnoreCase("退出")){
System.exit(0);
}
System.out.println("使用完毕请输入:退出");
}
}
}