简体   繁体   中英

Read a list of files into stream

I want to validate some links which are generated by my application. These generated files contain loads of lines I want to match with a regex to check if they are correct.

Where I'm stuck: I have a List of my files already declared and I want to open them into a stream so I can do some fancy Java coding with streams.

Right now my code looks like this:

   return !(Files.lines(Path.of(String.valueOf(FileList)))
      .anyMatch(v -> !v.matches(pattern));

The files are in the project's working directory so they only need a filename to access them. I want to read the files line by line to check for the incorrect lines. Is this the way to read a list of files with streams? If you know of any other way to make this work with streams please share. Many thanks!

I have a List of my files already declared

Assuming that is your FileList variable 1 , and that it is a List<String> (unspecified in question), then you would do something like this:

Predicate<String> matches = Pattern.compile(pattern).asMatchPredicate();
return FileList.stream().allMatch(f -> {
    try {
        return Files.lines(Paths.get(f)).allMatch(matches);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
});

1) Java naming convention specifies that variable names should start with lowercase letter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM