Reputation: 1553
I have the directory path being passed as an argument in Java program and the directory has various types of files. I want to retrieve path of text files and then further each text file. I am new to Java, any recommendation how to go about it?
Upvotes: 0
Views: 289
Reputation: 5958
Even though this is not an optimum solution you can use this as a starting point.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DirectoryWalker {
/**
* @param args
*/
private String extPtr = "^.+\\.txt$";
private Pattern ptr;
public DirectoryWalker(){
ptr = Pattern.compile(extPtr);
}
public static void main(String[] args) {
String entryPoint = "c:\\temp";
DirectoryWalker dw = new DirectoryWalker();
List<String> textFiles = dw.extractFiles(entryPoint);
for(String txtFile : textFiles){
System.out.println("File: "+txtFile);
}
}
public List<String> extractFiles(String startDir) {
List<String> textFiles = new ArrayList<String>();
if (startDir == null || startDir.length() == 0) {
throw new RuntimeException("Directory entry can't be null or empty");
}
File f = new File(startDir);
if (!f.isDirectory()) {
throw new RuntimeException("Path " + startDir + " is invalid");
}
File[] files = f.listFiles();
for (File tmpFile : files) {
if (tmpFile.isDirectory()) {
textFiles.addAll(extractFiles(tmpFile.getAbsolutePath()));
} else {
String path = tmpFile.getAbsolutePath();
Matcher matcher = ptr.matcher(path);
if(matcher.find()){
textFiles.add(path);
}
}
}
return textFiles;
}
}
Upvotes: 2
Reputation: 86409
Create a File object representing the directory, then use one of the list() or listFiles() methods to obtain the children. You can pass a filter to these to control what is returned.
For example, the listFiles() method below will return an array of files in the directory accepted by a filter.
public File[] listFiles(FileFilter filter)
Upvotes: 1
Reputation: 20442
Start by reading the File API. You can create a File from a String and even determine if it exists()
or isDirectory()
. As well as listing the children in that directory.
Upvotes: 0