0

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?

1
  • Try the suggestions below and post your source code if you need more help. Commented Sep 23, 2010 at 3:00

3 Answers 3

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.