Java输入一个文件名和一个字符串,判断该文件中是否存在该字符串,如果存在,输入该字符串所在的行数

package demo1;

import java.io.*;
import java.util.Scanner;

public class MyClass1
{

    String encoding = "UTF-8";
    public static void main(String[] args) throws IOException {
        Scanner input=new Scanner(System.in);
        System.out.println("请输入文件路径:");
        String path=input.nextLine();
        System.out.println("请输入子字符串:");
        String subString=input.nextLine();
        findStringInFile(path,subString);
    }

    public static void findStringInFile(String path,String subString) throws IOException{
        File file = new File(path);
        InputStreamReader read = new InputStreamReader(new FileInputStream(file),"UTF-8");
        BufferedReader bufferedReader = new BufferedReader(read);
        String line = null;
        int count=0;
        while ((line = bufferedReader.readLine()) != null) {            
            count++;
            //指定字符串判断处
            if (line.contains(subString)) {
                System.out.println("子字符串在第"+count+"行:");
                System.out.println(line);

            }
        }

    }

}

猜你喜欢

转载自blog.csdn.net/qq_40639185/article/details/100941569