I want to store the list of folders with name ending with MS present at PROJECT_LOCATION in a List ===>
ProcessBuilder processBuilder = new ProcessBuilder().directory(Paths.get(PROJECT_LOCATION)
.toFile())
.command("cmd.exe",
"/c",
"dir /b *MS;")
.inheritIO()
.redirectErrorStream(true);
Process process = processBuilder.start();
this much code is prinitng the names of folders ending with MS, but i want to store the values in a List
I tried =>
List<String> msList=new ArrayList<>();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
msList.add(line);
}
process.waitFor();
System.out.println("ok! "+ msList.size());
but the list size is printing to be 0. It is not reading the InputStream Lines. Does it not support for these kind of commands.....?
Console output===>
CartMS
CustomerMS
PaymentMS
ProductMS
ok! 0
Why are you starting an external program to list files when there's a much better alternative?
List<String> msList;
try (Stream<Path> stream = Files.walk(Paths.get(PROJECT_LOCATION), 1)) {
msList = stream.filter(Files::isRegularFile) // also filters out PROJECT_LOCATION itself
.map(f -> f.getFileName().toString())
.filter(f -> f.endsWith("MS"))
.toList(); // for older Java versions: .collect(Collectors.toList())
}
Or without streams:
List<String> msList = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(PROJECT_LOCATION), "*MB")) {
for (Path file : stream) {
msList.add(file.getFileName().toString());
}
}