Avatar ·

How to read a large text file line by line in Java without memory leak?

Hello everyone! I'm a beginner in Java and encountered a problem when reading a large log file (about 500 MB). I need to process each line separately, but when I try to read the entire file at once, the program crashes with OutOfMemoryError. Here's how I tried to do it: ```java import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { File file = new File("bigfile.log"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); // processing the line System.out.println(line); } scanner.close(); } } ``` But for large files this works very slowly and consumes a lot of memory. I've heard about Buffer