Parsing a Directory of files - Check for a String
- by i.h4d35
This is my first post here so kindly pardon any mistakes that I have. I'm still learning to find my way around Stack Exchange.
I am trying to write a Java program that tries to scan a Directory full of either .txt,.rtf or.doc files(and none other). The aim is to search all the files in the directory, and find out if a particular string exists in the file. If it does, it returns the string and the filename that it found the string in.
The aim of this program is, it is a project for school wherein the program scans the personal folders of call center employees to check if they have stored any CC/DC nos and if yes, report the folder name - to reduce CC fraud.
The search function was fairly straight forward and works when I individually specify the filename. However, the searching the directory and passing the files to the search function has me stumped.
I've posted my code so far, if you guys could look thru it and give me some feedback/suggestions, I'd really appreciate it. Thanks in advance
import java.io.*;
import java.util.*;
public class parse2{
void traverse(String directory) throws FileNotFoundException
{
File dir = new File(directory);
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i=0; i<children.length; i++)
{
//System.out.println("\n" + children[i]);
reader(children[i]);
}
}
}
void reader(String loc) throws FileNotFoundException
{ FileReader fr = new FileReader(loc);
BufferedReader br = new BufferedReader(fr);
Scanner sc = new Scanner(br);
char[] chkArray;
int chk=1;
char ch;
while(sc.hasNext())
{
String chkStr = sc.next();
chkArray = chkStr.toCharArray();
if ((chkArray[0]=='4')&&(chkStr.length()>13))
{ for(int i=0;i<chkArray.length;i++)
{ ch=chkArray[i];
if((ch=='0')||(ch=='1')||(ch=='2')||(ch=='3')||(ch=='4')||(ch=='5')||(ch=='6')||(ch=='7')||(ch=='8')||(ch=='9'))
{ chk=0;
continue;
}
else
{ chk=1;
break;
}
}
if(chk==0)
System.out.println("\n"+ chkStr);
}
else
if((chkArray[0]=='5')&&(chkStr.length()>13))
{ for(int i=0;i<chkArray.length;i++)
{ ch=chkArray[i];
if((ch=='0')||(ch=='1')||(ch=='2')||(ch=='3')||(ch=='4')||(ch=='5')||(ch=='6')||(ch=='7')||(ch=='8')||(ch=='9'))
{ chk=0;
continue;
}
else
{ chk=1;
break;
}
}
if(chk==0)
System.out.println("\n"+ chkStr);
}
else
if((chkArray[0]=='6')&&(chkStr.length()>13))
{ for(int i=0;i<chkArray.length;i++)
{ ch=chkArray[i];
if((ch=='0')||(ch=='1')||(ch=='2')||(ch=='3')||(ch=='4')||(ch=='5')||(ch=='6')||(ch=='7')||(ch=='8')||(ch=='9'))
{ chk=0;
continue;
}
else
{ chk=1;
break;
}
}
if(chk==0)
System.out.println("\n"+ chkStr);
}
}
}
public static void main(String args[]) throws FileNotFoundException
{
parse2 P = new parse2();
P.traverse("C:/Documents and Settings/h4d35/Desktop/javatest/chk");
}
}