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;

try{
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){
ioe.printStackTrace();
}finally{
try{
if(in != null) in.close();
if(fis != null) fis.close();
}catch(IOException ioe){ }
}
return false;
}
}

1 comment:

  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

    ReplyDelete