The Java read file display progress bar implementation

  • 2020-04-01 02:55:08
  • OfStack

Realize this function is simple, use the class has two: ProgressMonitorInputStream (mainly the entire class) and ProgressMonitor, they are on the javax.mail. Swing
The general idea is that you should first know the size of the entire file, and the size of the file that is currently read, and how to get the entire file size


ProgressMonitorInputStream monitor;

monitor = new ProgressMonitorInputStream(null, "Loading ",new FileInputStream("filename path"));
int all = monitor.available();//The size of the entire file
int in = monitor.read(data);//The size of the file per read

For example: you read STR = in.readline () one line at a time; The data = STR. Instr. GetBytes () + 1; Here, the +1 is mainly to get the number of bytes of the newline character, otherwise, the final gain will not be 100%


int readed=0;//Represents a file that has been read
reader+=in;//Read the file size incrementally

Calculation progress:


float process = (float) readed / all * 100;//Figure out the percentage

Window display:


progressMonitor.setNote("archived " + process + " %");//Displays on the progress bar


Related articles: