0

I have the following method the reads text file:

public static void readFile(String path) {

    BufferedReader br = null;
    try {
        String sCurrentLine;

        br = new BufferedReader(new FileReader(path));

        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine); // Progress indicator!
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

My file is really large ~ 700MB, I would love to be able to print progress indicator or percentage instead of printing the actual file on the console which really does not look good. Something probably like this:

========================================================== 100%

Any hint is appreciated.

Jeffry Hods
  • 59
  • 1
  • 7
  • Perhaps http://stackoverflow.com/questions/23167319/how-to-use-java-progress-bar-while-read-a-text-file could help? – GuiSim Apr 25 '16 at 20:27

1 Answers1

2

you have to change your System.out.println with progress. But for that you need couple of things.

  1. Get the file size using File object i.e.

    File f = new File (path); double fileSize = f.length(); br = new BufferedReader(new FileReader(path));

  2. Now inside the while loop. Everytime you read string you have to do something like this

    int percentRead = 0

    while ((sCurrentLine = br.readLine()) != null) {

    double bytesRead += (sCurrentLine.getBytes().length);
    
    int newPercentRead = (int)((bytesRead/fileSize) * 100);
    
    while (percentRead <= newPercentRead){
    
        System.out.print("#");
    
        percentRead++;
    
    }
    

    }

Its not tested, so you might have to tweak it around.

Em Ae
  • 8,167
  • 27
  • 95
  • 162