Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

java - Search a file for a String and return that String if found

How can you search through a txt file for a String that the user inputs and then return that String to the console. I've written some code that doesn't work below, but I hope it can illustrate my point...

public static void main(String[] args) {
  searchforName();
}

   private static void searchForName() throws FileNotFoundException {
    File file = new File("leaders.txt");
    Scanner kb = new Scanner(System.in);
    Scanner input = new Scanner(file);

    System.out.println("Please enter the name you would like to search for: ");
    String name = kb.nextLine();


    while(input.hasNextLine()) {
        System.out.println(input.next(name));
    }
}

The "leaders.txt" file contains a list of names.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a seperate Scanner to read the file line by line and do a match that way...

final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
   final String lineFromFile = scanner.nextLine();
   if(lineFromFile.contains(name)) { 
       // a match!
       System.out.println("I found " +name+ " in file " +file.getName());
       break;
   }
}

With regards to whether you should use a Scanner or a BufferedReader to read the file, read this answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...