Created
June 28, 2017 17:56
-
-
Save KrishnB/2e2e168d2585c1009000488acb4d3ef0 to your computer and use it in GitHub Desktop.
Search for a file in a project directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum FileExtension { | |
JAVA(".java"), | |
TEXT(".txt"), | |
SQL(".sql"), | |
FEATURE(".feature"), | |
EXCEL(".xls"); | |
private String fileExtension; | |
FileExtension(String fileExtension) { | |
this.fileExtension = fileExtension; | |
} | |
public String getFileExtension() { | |
return fileExtension; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class FileFinder { | |
private String path; | |
private boolean fileFound; | |
private List<File> allFiles; | |
private File fileToSearch; | |
private FileFinder(String path) { | |
this.path = path; | |
allFiles = new ArrayList<>(); | |
} | |
public static FileFinder fileFinder(String rootPath) { | |
return new FileFinder(rootPath); | |
} | |
public static FileFinder fileFinder() { | |
return new FileFinder(System.getProperty("user.dir")); | |
} | |
public List<File> find(FileExtension fileExtension) { | |
collectFiles(new File(path),fileExtension.getFileExtension()); | |
return allFiles; | |
} | |
public File find(String fileName, FileExtension fileExtension) { | |
collectFile(new File(path),fileName,fileExtension.getFileExtension()); | |
return fileToSearch; | |
} | |
private void collectFiles(File rootFile, String fileExtensionToSearch) { | |
if(rootFile.exists() && rootFile.isDirectory()) { | |
File[] files = rootFile.listFiles(); | |
assert files != null; | |
for(File file : files) { | |
if(!file.isDirectory()) { | |
fileFound = file.getName().endsWith(fileExtensionToSearch); | |
if(fileFound) { | |
allFiles.add(file); | |
} | |
} else { | |
collectFiles(file,fileExtensionToSearch); | |
} | |
} | |
} | |
} | |
private void collectFile(File rootFile, String fileName, String fileExtensionToSearch) { | |
if(rootFile.exists() && rootFile.isDirectory()) { | |
File[] files = rootFile.listFiles(); | |
assert files != null; | |
for(File file : files) { | |
if(!file.isDirectory()) { | |
fileFound = file.getName().contains(fileName) && file.getName().endsWith(fileExtensionToSearch); | |
if(fileFound) { | |
fileToSearch = file; | |
break; | |
} | |
} else { | |
collectFile(file,fileName,fileExtensionToSearch); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment