Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to check if a file contains a given string?

 
Sajee Joseph
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dirty and untested. This may work. One method is probably non-existant. Usage: java Grep filename searchstring
 
greg philpott
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//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
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If we have the whole file in a String, indexOf("hello") will work. It returns -1 if the String does not contain it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic