Java:我们如何进一步简化文件的Java8流逻辑
我们如何组合下面的两个流逻辑:Java:我们如何进一步简化文件的Java8流逻辑,java,file,java-stream,simplify,Java,File,Java Stream,Simplify,我们如何组合下面的两个流逻辑: public void filterRecord(File inputDirectory) throws IOException { if (inputDirectory.exists() && !inputDirectory.isDirectory()) { List<Path> pathStreams = Files.list(Paths.get(inputDirectory.getAbso
public void filterRecord(File inputDirectory) throws IOException {
if (inputDirectory.exists() && !inputDirectory.isDirectory()) {
List<Path> pathStreams = Files.list(Paths.get(inputDirectory.getAbsolutePath()))
.filter(path -> path.toString().endsWith(".csv"))
.collect(Collectors.toList());
for (Path filePath : pathStreams) {
Files.lines(filePath)
.filter(line -> (line != null && !line.isEmpty()))
.filter(line -> "10".equals(line.substring(0, line.indexOf(",")).trim()))
.forEach(System.out::println);
}
}
}
public void filterRecord(文件输入目录)引发IOException{
if(inputDirectory.exists()&&!inputDirectory.isDirectory()){
List pathStreams=Files.List(path.get(inputDirectory.getAbsolutePath()))
.filter(path->path.toString().endsWith(“.csv”))
.collect(Collectors.toList());
对于(路径文件路径:pathStreams){
Files.lines(文件路径)
.filter(line->(line!=null&&!line.isEmpty())
.filter(line->“10”).equals(line.substring(0,line.indexOf(“,”).trim())
.forEach(System.out::println);
}
}
}
在上面的代码中,这两个流正在参与
…
.flatMap(filePath->Files.lines(filePath))。
会更容易。。。但是你不能,除非你创建了一个方法来处理并且不进一步抛出IOException
。类似于尝试{return Files.lines(path);}catch(IOException e){e.printStackTrace();return Stream.empty();//或RuntimeException}
首先,为什么要处理文件
?直接使用路径输入单词。使方法签名成为路径
。2020年几乎不需要使用java.io.File
。其次,请研究流上的flatMap
操作。
public void fileStreamsFilter(Path inputDirectoryPath) throws IOException {
if (Files.exists(inputDirectoryPath) && Files.isDirectory(inputDirectoryPath)) {
Files.list(inputDirectoryPath).filter(path -> path.toString().endsWith(".csv"))
.flatMap(path -> {
try {
return Files.lines(path);
} catch (IOException ioException) {
log.error(ioException.getMessage(), ioException);
}
return null;
})
.filter(line -> (line != null && !line.isEmpty()))
.filter(line -> "10".equals(line.substring(0, line.indexOf(",")).trim()))
.forEach(log::info);
}
}