Java enters a file name and a string to determine whether the string exists in the file, and if so, enter the number of lines where the string is located

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);

            }
        }

    }

}

Guess you like

Origin blog.csdn.net/qq_40639185/article/details/100941569