Memory error, java empty space

I am trying to read a log file with more than 4 million lines and larger than 400 MB, but I get a memory error: java heap space . This is my code:

File file = new File("C:\\file.log");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuilder stringBuffer = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }

I tried to increase the heap memory to 1 GB, but still get this message. What would be the possible reason?

+4
source share
1 answer

Well, you already have a key reading the comments you received.

Explanation of the problem:

Your log file is 400 MB in size. Please note that this is measured in bytes. Now you are reading it line by line with line = bufferedReader.readLine(), converting some bytes to a string.

A String Java a char[]. a char Java 2 ! , 800 . , JVM , , 1 .

, StringBuffer (: StringBuilder ) char[], ( ). . , 400 char[] 512 . : A char 2 .

, ? : !

:

class LogAnalyzer {
    private final File logFile;

    LogAnalyzer(File logFile) {
        this.logFile = logFile;
    }

    void analyze() throws IOException {
        try(FileReader fileReader = new FileReader(logFile)) {
            try(BufferedReader bufferedReader = new BufferedReader(fileReader)) {
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    analyzeLine(line);
                }
            }
        }
    }

    private void analyzeLine(String line) {
        // do whatever you need here
    }
}

, LogAnalyzer / .

+15

All Articles