Write a Java program, with a specific suffix named conditional, in the specified directory recursively search for files, and then generate a list of files.
1ImportJava.io.File;
2ImportJava.util.ArrayList;
3ImportJava.util.List;
4
5 PublicclassFilelistgenerator {
6
7//The FileList class can look for files with all specified file suffix names under the specified path and generate a list of files-list<file>
8
9Filelistgenerator (File path) {//if the file suffix name is not specified
Tenif(Path.isdirectory () && Path.isabsolute ()) {
One This. Entrypath = path;
A}Else{
-ThrowNewIllegalArgumentException ("The given path is not absolute directory!!");
-}
the This. Specifysuffix =false;//no arguments passed in the specified suffix name, so set Specifysuffix to False
-FileList =NewArraylist<file> ();//List of initialization files
-}
-
+Filelistgenerator (File path, String filenamesuffix) {//If a file suffix name is specified
-if(Path.isdirectory () && Path.isabsolute ()) {
+ This. Entrypath = path;
A}Else{
atThrowNewIllegalArgumentException ("The given path is not absolute directory!!");
-}
- This. Specifysuffix =true;
- This. Filenamesuffix = Filenamesuffix;
-FileList =NewArraylist<file> ();//List of initialization files
-}
in
-PrivateFile Entrypath;//entry path to search for files
toPrivateList<file> fileList;//The object type is a list of file, and the initialization of the list is done in the constructor method
+PrivateBooleanSpecifysuffix;//whether to specify the suffix name of the search target file to turn on the search for specific files feature
-PrivateString Filenamesuffix;
the
* PublicList<file> Getfilelist () {
$ This. Fillfilelist (Entrypath);
Panax NotoginsengreturnFileList;
-}
the
+PrivatevoidFillfilelist (File absolutepath) {
A //look for the specified suffix or normal file and populate the file list filelist
thefile[] Filelistindir = Absolutepath.listfiles ();//to save a list of all files & directories under the specified path, noting that the directory is also a file type
+
-if( This. Specifysuffix) {
$ for(inti = 0; i < filelistindir.length; i++) {
$if(Filelistindir[i].isfile ()) {//determines whether the current item is a file, or a directory
- if(Filelistindir[i].getabsolutepath (). EndsWith ( This. Filenamesuffix)) {
- This. Filelist.add (Filelistindir[i]);
the}
-}Else{
Wuyi This. Fillfilelist (Filelistindir[i]);//if the current item in the array filelistindir is not a file but a directory, the Recursive method Fillfilelist () is called .
the}
-}
Wu}Else{
- for(File X:filelistindir) {//If you do not specify a file suffix, the process of finding all the files is simple ...
Aboutif(X.isfile ()) {
$ This. Filelist.add (x);
-}Else{
- This. fillfilelist (x);
-}
A}
+}
the
-Filelistindir =NULL;//The temporary file list is now complete using
$}
the }
Java: Search for files with specific suffix names