HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Extracting text data from a file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filetextextractingfromdata

Problem

Can I make this program that extracts text data from a file (size in MBs) even better performance-wise? I need to reduce the execution time.

import java.io.*;

public class ReadData {

    public static void main(String[] args) {

        FileReader input = null;
        BufferedReader br = null;

        try {

            input = new FileReader("C:/Projects/Test/HPCamDrv.log");
            br = new BufferedReader(input);
            String str;

            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
        }

        catch (IOException e) {
            e.printStackTrace();
        }

        finally {

            try {
                input.close();
                br.close();
            }

            catch (IOException x) {
                x.printStackTrace();
            }

        }
    }
}

Solution

It's a pretty small and straight-forward program and not really much to improve on. ChrisWue also brings up the good point that printing to stdout for every line is costly but if you need to print it to stdout there's not much to do about it.

But one thing you can actually do is implement Java's try-with resources which will ensure your resources are closed at the end of the statement, so you can get rid of all your .close() calls and your finally block.

Context

StackExchange Code Review Q#43372, answer score: 3

Revisions (0)

No revisions yet.