AspiringGeek
AspiringGeek

Reputation: 95

What is the most efficient way to list a directory?

So my title might not be the most descriptive but essentially I am doing this in one class:

What the above script does, is that it produces a bunch of files in the current working directory. In a second script what I want to be able to do is retrieve all the output files of extension (.example), retrieve their paths, concatenate them in a comma-seperated list, and feed it into a second script.

    //process 2
    launchSecondScript("perl --list-of-comma-seperated-file paths

What is the most efficient way to retrieve that comma-seperated string of file paths and provision it to a second function. I also know the directory where the files will be outputted so that is not a problem.

Upvotes: 4

Views: 236

Answers (2)

Stewart Evans
Stewart Evans

Reputation: 1536

Similar to Elliot's response here is a java7 (nio) version

public static String listFiles(String dir, String extensionToMatch){

    StringBuilder fileList = new StringBuilder();

    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(dir))) {
        for (Path path : directoryStream) {
            if(path.toString().endsWith(extensionToMatch)){
                if(fileList.length() != 0){
                    fileList.append(",");
                }
                fileList.append(path.toString());
            }
        }
    } catch (IOException ex) {}

    return fileList.toString();
}

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201429

I might use a simple Java function to do this

private static String concatenateFilePaths(
    String directory, String extension) {
  StringBuilder sb = new StringBuilder();
  File f = new File(directory);
  if (f != null && f.isDirectory()) {
    File[] files = f.listFiles();
    for (File file : files) {
      if (file != null
          && file.getName().endsWith(extension)) {
        if (sb.length() > 0) {
          sb.append(", ");
        }
        sb.append('"');
        sb.append(file.getPath());
        sb.append('"');
      }
    }
  }
  return sb.toString();
}

I then might use it like so

System.out.println(concatenateFilePaths("/tmp/test/",
    ".example"));

On my system ls /tmp/test

a.example  b.example  c

Result of above call

"/tmp/test/a.example", "/tmp/test/b.example"

Upvotes: 2

Related Questions