What I want to do in my application is that let user chooses a series of text files by using filechooser, and then my application will filter some of them if it does't contain specified subString.
It's my code by using lambda:
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("choose files");
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt"));
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("CSV files (*.csv)", "*.csv"));
List<File> targetList = fileChooser.showOpenMultipleDialog(primaryStage);
if (targetList == null) {
System.out.println("targetList none");
}
targetList.parallelStream()
.filter(f->{
try {
return new BufferedReader(new FileReader(f)).lines()
.anyMatch(line-> (line.indexOf(",")!=-1));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
)
.collect(Collectors.toList());
It wroks, but not perfect! Because BufferedReader is never closed and I need to wrap it with a Buiky catch statesment.
Anyone could give tips to improve it in elegant way?