简体   繁体   中英

How do I make progress bars update according to the reading progress of a file?

I want the progress bars to show the percentage of file being read but I seem to cannot accomplish this with my code. The progress bars won't start at all. I think my logic is a mess. Any suggestions on how to fix this problem?

Code below:

    public void run()
  {
     progressBar.setIndeterminate(false);

     try
     {
        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);

        long fileSize = fileName.length();

        String line = "";
        String concatString = "";

        keepGoing = true;
        while((((line = br.readLine()) != null)) && keepGoing == true) 
        {
           concatString += line; //concatenated string
           int stringLength = concatString.length(); //length of concatenated string
           int progressNum = (int) (stringLength / fileSize); //value to update progress bar 
              try
              {
                 Thread.sleep(1000);
              }
              catch(InterruptedException ie)
              {
                 ie.printStackTrace();
              }                                              
           progressBar.setValue(progressNum);                                         
        } 
        progressBar.setString("Finished file read...");
        progressBar.setIndeterminate(true); 

       synchronized(obj)
       {
          if(keepGoing == true)
          {
             keepGoing = false; 
             progressBar.setString("Halted!");                
          }                        
       }

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

  } 

Please keep in mind I am a beginner programmer. Edit: I already set the minimum and maximum values in my progressbar constructor(0, 100).

you should convert this to percentage

 int progressNum = (int) (stringLength / fileSize); 

by doing

int progressNum = (int) (stringLength *100 / fileSize); 

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM