互联网技术 · 2024年3月30日

分享Java代码:实现读取文件并显示进度条

当读取一个大文件时,一时半会儿无法看到读取结果,就需要显示一个进度条,是程序员明白已经读了多少文件,可以估算读取还需要多少时间,下面的代码可以实现这个功能

实现这个功能比较简单,用到的类有两个:ProgReSSMoniTorInputStReaM(主要是整个类) 和 ProgReSSMoniTor ,它们在javax.swing中

大体思路,你要首先知道整个文件的大小,和当前已经读取文件的大小,获得整个文件大小的方法
ProgReSSMoniTorInputStReaM MoniTor;
MoniTor = new ProgReSSMoniTorInputStReaM(null, “loading “,new FilEINputStReaM(“filenaMe path”));
int all = MoniTor.avAIlable();//整个文件的大小
int in = MoniTor.Read(data);//每次读取文件的大小

例如:你每次读一行stR=in.ReadLine();则data=stR.instR.getBytes()+1;这里+1,主要是为了获得换行符的字节数,否则,最后获得的进步无法达到100%
int Readed=0;//表示已经读取的文件
ReadeR+=in;//累加读取文件大小

float ProceSS = (float) Readed / all * 100;// 算出百分比

ProgReSSMoniTor.setNote(“aRcHived ” + ProceSS + ” %”);// 显示在进度条上

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册