Reputation: 389
this is a semi homework and I've been trying for ages but without luck,basically I'm doing a Search engine-Like program,where i read files in my directory + their sub directory's and Read the text files to search for a match,i searched endlessly but without clear answer so I'd appreciate if any one could help.
this was my best try but the problem with it that it only took the files from the sub directory and ignored the main/root directory,tried to figure out why but couldn't.
public void indexDirectory(File dir) {
for(int i=0;i<50;i++)
ls[i]=new LinkList();//array of Linked lists to store addresses of each Linked list that has a file
try{
files= dir.listFiles();
for (int i = 0; i < files.length; i++) {
if(files[i].isDirectory())
indexDirectory(files[i]);
if(files[i].isFile()){
if(files[i]!=null)
indexFile(files[i]);
} //end if(isFile)
} //end For loop
}catch(FileNotFoundException e){
System.out.println("error ");
}}
second version after serching the web and trying to emulate what i found,but didn't work sadly.
public void indexDirectory(File dir) {
for(int i=0;i<50;i++)
ls[i]=new LinkList();
try{
if(dir.isFile()){
indexFile(dir); //this method takes each directory and read the words and save them in
// array of linked list
}
else if(dir.isDirectory()){
files= dir.listFiles();
if(files!=null) {
for (int i = 0; i < files.length; i++) {
if(files[i].isDirectory()){
indexDirectory(files[i]); //recursive call
}}
}catch(FileNotFoundException e){
System.out.println("error ");
}}
Upvotes: 1
Views: 318
Reputation: 711
In the first version, you loop through the entire file.length and check only for file.isDirectory and after that (ie. after all files/folders have been traversed) you check if it is a file. That's why you cannot read through current directory's files. Simply put the
if(files[i].isFile()){
if(files[i]!=null)
indexFile(files[i]); //the method to read from these files and save to array of lists.
}
block in for loop and it should work in the first version. One more thing I didn't understand the purpose of ls variable here.
Upvotes: 1