Find a string (or a line) in a txt File Java

前端 未结 5 936
忘掉有多难
忘掉有多难 2020-12-09 06:03

let\'s say I have a txt file containing:

john
dani
zack

the user will input a string, for example \"omar\" I want the program to search tha

相关标签:
5条回答
  • use String.contains(your search String) instead of String.endsWith() or String.startsWith()

    eg

     str.contains("omar"); 
    
    0 讨论(0)
  • 2020-12-09 06:32

    You can go other way around. Instead of printing 'does not exist', print 'exists' if match is found while traversing the file and break; If entire file is traversed and no match was found, only then go ahead and display 'does not exist'.

    Also, use String.contains() in place of str.startsWith() or str.endsWith(). Contains check will search for a match in the entire string and not just at the start or end.

    Hope it makes sense.

    0 讨论(0)
  • 2020-12-09 06:46

    Just read this text file and put each word in to a List and you can check whether that List contains your word.

    You can use Scanner scanner=new Scanner("FileNameWithPath"); to read file and you can try following to add words to List.

     List<String> list=new ArrayList<>();
     while(scanner.hasNextLine()){
         list.add(scanner.nextLine()); 
    
     }
    

    Then check your word is there or not

    if(list.contains("yourWord")){
    
      // found.
    }else{
     // not found
    }
    

    BTW you can search directly in file too.

    while(scanner.hasNextLine()){
         if("yourWord".equals(scanner.nextLine().trim())){
            // found
            break;
          }else{
           // not found
    
          }
    
     }
    
    0 讨论(0)
  • 2020-12-09 06:46

    Read the content of the text file: http://www.javapractices.com/topic/TopicAction.do?Id=42

    And after that just use the textData.contains(user_input); method, where textData is the data read from the file, and the user_input is the string that is searched by the user

    UPDATE

    public static StringBuilder readFile(String path) 
     {       
            // Assumes that a file article.rss is available on the SD card
            File file = new File(path);
            StringBuilder builder = new StringBuilder();
            if (!file.exists()) {
                throw new RuntimeException("File not found");
            }
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(file));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
           return builder;
        }
    

    This method returns the StringBuilder created from the data you have read from the text file given as parameter.

    You can see if the user input string is in the file like this:

    int index = readFile(filePath).indexOf(user_input);
            if ( index > -1 )
                System.out.println("exists");
    
    0 讨论(0)
  • 2020-12-09 06:46

    You can do this with Files.lines:

    try(Stream<String> lines = Files.lines(Paths.get("...")) ) {
        if(lines.anyMatch("omar"::equals)) {
      //or lines.anyMatch(l -> l.contains("omar"))
            System.out.println("found");
        } else {
            System.out.println("not found");
        }
    }
    

    Note that it uses the UTF-8 charset to read the file, if that's not what you want you can pass your charset as the second argument to Files.lines.

    0 讨论(0)
提交回复
热议问题