Home  >  Article  >  Java  >  How to implement the progress bar of Java file reading

How to implement the progress bar of Java file reading

PHPz
PHPzforward
2023-04-19 23:16:05861browse

Run screenshot

How to implement the progress bar of Java file reading

Related code

Read file class

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();
		}
	}
}

Test class

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();
	}
}

Brief description

This example is very simple, that is, every time the file is read, the progress of the progress bar is updated, which is similar to accumulating a number from 0, each time the number Update, the progress of the progress bar is also updated until it accumulates to the maximum value. It's best to set it proportionally here, otherwise the progress bar may look a little strange. For larger files, you can also use threads to update the progress every once in a while. If you are interested here, you can try it.

Supplementary: Please note that the path problem here is relative to the current path. It is best to use relative paths to facilitate program migration. If you are not sure, you can use an absolute path, which is the exact address of the entire file on the disk.

The above is the detailed content of How to implement the progress bar of Java file reading. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete