1

I'm reading a text file line by line and converting it into a string.

I'm trying to figure out how to check if the last line of the file is a specific word ("FILTER").

I've tried to use the endsWith(String) method of String class but it's not detecting the word when it appears.

Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
Moshe
  • 205
  • 1
  • 6
  • 8
  • You should show the code you're using... It seems to me you may have missed something in the code that is causing your issues. – Romain Mar 21 '11 at 12:53
  • I agree with Romain. Can you also show an example file? – Zlatko Mar 21 '11 at 12:55
  • 3
    possible duplicate of [Java: Quickly read the last line of a text file?](http://stackoverflow.com/questions/686231/java-quickly-read-the-last-line-of-a-text-file) – dogbane Mar 21 '11 at 12:55
  • dogbane this is not a duplicate ,he needs to check whether a word is present in last line of a file – Deepak Mar 21 '11 at 12:56

4 Answers4

4

Rather naive solution, but this should work:

String[] lines = fileContents.split("\n");
String lastLine = lines[lines.length - 1];
if("FILTER".equals(lastLine)){
// Do Stuff
}

Not sure why .endsWith() wouldn't work. Is there an extra newline at the end? (In which case the above wouldn't work). Do the cases always match?

Tom Elliott
  • 1,908
  • 1
  • 19
  • 39
1

.trim() your string before checking with endsWith(..) (if the file really ends with the desired string. If not, you can simply use .contains(..))

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

With

myString.endsWith("FILTER") 

the very last characters of the last line are checked. Maybe the method

myString.contains("FILTER")

is the right method for you? If you only want to check the last ... e.g.20 chars try to substring the string and then check for the equals method.

Java_Waldi
  • 924
  • 2
  • 12
  • 29
0
   public static boolean compareInFile(String inputWord) {     

         String word = "";     

        File file = new File("Deepak.txt");     
        try {     
            Scanner input = new Scanner(file);     
            while (input.hasNext()) {     
                word = input.next();     
                if (inputWord.equals(word)) {     
                    return true;     
                }     
            }     

        } catch (Exception error) {     
       }     
        return false;     
   }     
Deepak
  • 2,094
  • 8
  • 35
  • 48