Issue
I want to know if there is any way I can read in a file that contains tens of thousands of lines and only process every nth line (the interval does not change and is constant throughout). More to the data in the file, each line has the potential to be very large as well (few thousand words long).
I am aware that I could probably do this with a reader and then just do a loop at the end to get to the next nth interval, but I want to know if there is a better way of doing this. I looked into using a stream but I cannot seem to find a way to only look at every nth line. I cannot find anything in the documentation that suggest the stream keeps a record of what line of the file it is currently looking at, but if this was accessible I could use this.
Currently, I could store all the lines in an array and then modulus this, but I still have the issue of storing all this data that I do not care about.
Solution
Just use a filter on the stream of lines...
public class EveryNthLine {
static int N = 4; // pick a number
static int line = 0; // or 1 depends on how you define Nth
public static void main(String[] args) throws IOException {
Files.lines(Path.of(args[0]), StandardCharsets.UTF_8)
.filter(s -> line++ % N == 0)
.forEach(System.out::println);
}
}
Answered By - swpalmer
Answer Checked By - Robin (JavaFixing Admin)