javaloopskotlinfilereaderfile-processing

loop through the lines which are specified through a parameter


I have a chunk of code below which reads from a file in s3 and processes all the lines. The file doesn't have any line numbers in it. However, I want the code to process only specific lines of file. How should I approach that? Note: The start line number and end line number are being passed as parameter. Below is the current code

var counter=0
s3Service.getS3FileBufferedReader(s3File).use { s3BufferedReader ->

            s3BufferedReader.useLines { lines ->

                lines.forEach {
                    // Process each line


                    val transaction = Transaction(it)

                    // does some processing 

                    counter ++
                    log.info("Line number: ${counter}")
                }
            }
        }```

What I'm trying to achieve is, instead of processing the whole file, I want to process lines from 10 to 20. The catch is, the file only has data and no line numbers in it.

Solution

  • You could use Sequence#drop(Int) and Sequence#take(Int) for this:

    lines.drop(start - 1).take(end - start + 1).forEach {
        // do your stuff with the line
    }