I am trying to chunk a text file (lets say, a log file), to only pick a certain no. of rows at a time for processing (lets say, we are splitting log file into smaller ones). I wrote this code in imperative style:
package utils; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.function.Consumer; public class FileUtils { public static void main(String[] args) { readFileInChunks("D:\\demo.txt", 10000, System.out::println); } public static void readFileInChunks(String filePath, int chunkSize, Consumer<StringBuilder> processor) { try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { StringBuilder lines = new StringBuilder(); String line, firstLine = null; int i; for (i = 0; (line = br.readLine()) != null; i++) { if (firstLine == null) firstLine = line; lines.append(line + "\n"); if ((i + 1) % chunkSize == 0) { processor.accept(lines); lines = new StringBuilder(firstLine + "\n"); } } if (lines.toString() != "") { processor.accept(lines); } br.close(); } catch (IOException e) { e.printStackTrace(); } } } All these years, I spent coding in iterative style and I can't come up with Java 8 streams based functional style implementation of this method.
Is it possible to make readFileInChunks method return a Stream<String> of chunks? Or, implement readFileInChunks in a functional way?
br.close()manually when you declarebrwithin thetry(…)statement. That’s the whole purpose of the language feature.