Java Reference
In-Depth Information
}
return false;
}
}
Listing 8-20 ' s FindAll class declares main() , findAll() , and find() class
methods.
main() validatesthenumberofcommand-linearguments,whichmustbetwo.The
firstargumentidentifiesthestartinglocationwithinthefilesystemforthesearch,andis
used to construct a File object. The second argument specifies search text. main()
thenpassesthe File objectandthesearchtextto findAll() toperformasearchfor
all files containing this text.
The recursive findAll() method first invokes listFiles() on the File ob-
ject passed to this method, to obtain the names of all files in the current directory. If
listFiles() returnsnull,meaningthatthe File objectdoesn'trefertoanexisting
directory, findAll() returns false and a suitable error message is output.
Foreachnameinthereturnedlist, findAll() eitherrecursivelyinvokesitselfwhen
thenamerepresentsadirectory,orinvokesthe find() methodtosearchthefileforthe
text; the file's pathname string is output when the file contains this text.
The find() method first opens the file identified by its first argument via the
FileReader class, and then passes the FileReader instance to a
BufferedReader instancetoimprovefile-readingperformance.Itthenentersaloop
that continues to read characters from the file until the end of the file is reached.
Ifthecurrentlyreadcharactermatchesthefirstcharacterinthesearchtext,aninner
loopisenteredtoreadsubsequentcharactersfromthefileandcomparethemwithsub-
sequentcharactersinthesearchtext.Whenallcharactersmatch, find() returnstrue.
Otherwise,thelabeledcontinuestatementisusedtoskiptheremainingiterationsofthe
innerloopandtransferexecutiontothelabeledouterloop.Afterthelastcharacterhas
been read and there's still no match, find() returns false.
Nowthatyouknowhow FindAll works,you'llprobablywanttotryitout.Thefol-
lowing examples show you how I might use this application on my XP platform:
java FindAll \prj\dev OpenGL
Thisexamplesearchesthe \prj\dev directoryonmydefaultdrive(C:)forallfiles
that contain the word OpenGL (case is significant) and generates the following output:
Search WWH ::




Custom Search