aspose file tools*
The moose likes Beginning Java and the fly likes How to check if a file contains a given string? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to check if a file contains a given string?" Watch "How to check if a file contains a given string?" New topic
Author

How to check if a file contains a given string?

Sajee Joseph
Ranch Hand

Joined: Jan 17, 2001
Posts: 200
Hi,
How to check if a file contains a given string?.
say for instance i'd like to know if a file contains a string "hello" in it.
How do i do that?
regards
..saj
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
Dirty and untested. This may work. One method is probably non-existant. Usage: java Grep filename searchstring
greg philpott
Ranch Hand

Joined: Nov 10, 2000
Posts: 73
//You can do something like this:
//open the file with an approriate java.io class:
RandomAccessFile f = new RandomAccessFile("yourfile.txt", "r");
//read the file contents into a String:
String s= f.readUTF();
//now use utility class to break String into tokens:
StringTokenizer st = new StringTokenizer(s);
//now go through tokens(words) in file to test for "hello"
while (st.hasMoreTokens()) {
if(st.nextToken().equals("hello"))
System.out.println("File contains string: hello!");
}

[This message has been edited by greg philpott (edited September 26, 2001).]
James Gray
Ranch Hand

Joined: Sep 10, 2001
Posts: 30
If we have the whole file in a String, indexOf("hello") will work. It returns -1 if the String does not contain it.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to check if a file contains a given string?