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

5 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. 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

    ReplyDelete
  3. There are times when I find it difficult to make decisions, but still have to do. I know people always have emotions so that there is no justice. But I still hope.
    catmario4.com

    ReplyDelete
  4. 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