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;
}
}

2 comments:

  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
  2. The cash is accessible considerably speedier than it is with a bank credit. Unsecured trader loans are extraordinarily an extraordinary alternative for retail and eatery shippers, not just on the grounds that these kinds of organizations can barely be supported by the conventional bank, yet in addition on account of the quick liquidity and straightforward process. Payday Loans

    ReplyDelete