Skip to main content
edited tags
Link
Source Link

Java file analyzer byte-by-byte

This is part of this topic.
Problem:
I need to read a file with BigIntegers and make some analysis "on-the-fly" with each read number (get prime numbers count, get armstrong numbers count). Right now I have this code, but it works very slow:

package ee.raintree.test.numbers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;

import ee.raintree.test.numbers.utils.MathUtils;

public class FileAnalyzer {
    private static final char SEPARATOR = ' ';
    private File file;
    private int armstrongNumbersCount;
    private int primeNumbersCount;

    public FileAnalyzer(File file) {
        this.file = file;
    }

    public void analyze() throws FileNotFoundException, IOException {
        countNumbers();
    }

    public int getArmstrongNumbersCount() {
        return armstrongNumbersCount;
    }

    public int getPrimeNumbersCount() {
        return primeNumbersCount;
    }

    private void countNumbers() throws FileNotFoundException, IOException {
        StringBuilder numberSb = new StringBuilder();
        try (FileInputStream fis = new FileInputStream(file)) {
            char currentChar;
            while (fis.available() > 0) {
                currentChar = (char) fis.read();
                if (currentChar == SEPARATOR) {
                    analyzeNumber(new BigInteger(numberSb.toString()));
                    numberSb = new StringBuilder();
                    continue;
                }
                numberSb.append(currentChar);
            }
            if (numberSb.length() > 0) {
                analyzeNumber(new BigInteger(numberSb.toString()));
            }
        }
    }

    private void analyzeNumber(BigInteger number) {
        if(MathUtils.isArmstrongNumber(number)) {
            armstrongNumbersCount++;
        }
        if(MathUtils.isPrime(number)) {
            primeNumbersCount++;
        }
    }
}

How can I speed up this process? As I was informed - it is lack of buffering.