Reputation: 95
So my title might not be the most descriptive but essentially I am doing this in one class:
In another function within the same class, I would like to provision certain files that I have created from my first script into another script
//process 1
launchOnCommandLine("perl --arg1 -arg2");
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
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
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