Data AccessCore JavaApp FrameworksViewTestingBuildingDeploymentDev ToolsSecurityOpinions

Tuesday, April 14, 2009

Check if a file contains a string

I recently wrote some java code to check if a file contains a string.

public class FileUtilities {

* Returns true if the file exists and contains aString, false otherwise.
* @param file
* @param aString
* @return
* @throws FileNotFoundException
public static boolean fileContainsString(File file, String aString) throws FileNotFoundException{

FileInputStream fis = null;
BufferedReader in = null;

fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));

String currentLine = "";
while ((currentLine = in.readLine()) != null) {
if(currentLine.indexOf(aString) > 0) return true;

}catch(IOException ioe){
if(in != null) in.close();
if(fis != null) fis.close();
}catch(IOException ioe){ }
return false;


  1. Hi there,

    the line
    if(currentLine.indexOf(aString) > 0) return true;

    should be

    if(currentLine.indexOf(aString) > -1) return true;

    since 0 is a absolutly valid index

  2. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Java Training in Chennai | Core Java Training in Chennai

    Online Java Training Java Online Training | Java J2EE Online Training | JavaEE Training Institute in Chennai