您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java文件读取的进度条怎么实现

2024/6/18 0:49:16发布23次查看
运行截图
相关代码读取文件类
package test;import java.io.file;import java.io.fileinputstream;import java.io.fileoutputstream;import java.io.ioexception;import javax.swing.progressmonitor;import javax.swing.progressmonitorinputstream;public class readfile{ private file target, output; public readfile(file target, file output) { this.target = target; this.output = output; } /* * 这里需要设置 progressmonitor对象的最小值和最大值。 * 当超过最大值时,进度条正好结束。 * 需要手动调用 setprogress 方法,更新进度。 * 更新的方法有很多种,可以自己计算相对大小,这里我取一个简单的方法。 * 直接利用文件的大小并进行累加。 * */ public void readfile() throws interruptedexception { byte[] b = new byte[124]; try( fileinputstream in = new fileinputstream(target); fileoutputstream out = new fileoutputstream(output); progressmonitorinputstream pmi = new progressmonitorinputstream(null, "读取", in)) { progressmonitor monitor = pmi.getprogressmonitor(); monitor.setminimum(0); monitor.setmaximum((int) (target.length())); int progress = 124; int sum = 0; while (in.read(b) != -1) { out.write(b); //此处代码在控制台打印当前源文件。 // string s = new string(b); // system.out.println(s); thread.sleep(1000); sum += progress; monitor.setprogress(sum); } } catch(ioexception e) { e.printstacktrace(); } }}
测试类
package test;import java.io.file;public class test { public static void main(string[] args) throws interruptedexception { readfile read = new readfile(new file("./src/test/readfile.java"), new file("./output.java")); read.readfile(); }}
简要说明这个例子很简单,就是每次读取文件后,更新进度条的进度,就类似于,从 0 累加一个数,每次数字更新,进度条的进度也更新,直到累加到最大值为止。这里最好设置成比例,否则可能进度条会有点奇怪。对于较大的文件,也可以使用线程,每隔一段时间,更新一下进度,这里感兴趣的可以尝试一下。
补充:注意一下,路径问题,我这里是相对于当前路径的,最好使用相对路径,这样方便程序迁移。如果不太清楚,可以使用绝对路径,就是整个文件在磁盘中的准确地址。
以上就是java文件读取的进度条怎么实现的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product