如何在文件传输时创建进度条

import java.awt.Component; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.swing.JOptionPane; import javax.swing.ProgressMonitorInputStream; public class buckUpFile { private Component parentComponent; public void copyFile() { File srcFolder = new File( "C:\\Users\\ALLEN\\Workspace\\FINAL_LCTP_WORKBENCE_1.5"); File destFolder = new File( "C:\\Data Programing\\COPY_OF_FINAL_LCTP_WORKBENCE_1.5"); if (!srcFolder.exists()) { JOptionPane.showMessageDialog(null, "Directory does not exist."); System.exit(0); } else { try { copyFolder(srcFolder, destFolder); } catch (IOException e) { e.printStackTrace(); System.exit(0); } } JOptionPane.showMessageDialog(null, "Back up request has been completed"); } public void copyFolder(File src, File dest) throws IOException { if (src.isDirectory()) { if (!dest.exists()) { dest.mkdir(); } String files[] = src.list(); for (String file : files) { File srcFile = new File(src, file); File destFile = new File(dest, file); copyFolder(srcFile, destFile); } } else { InputStream in = new BufferedInputStream( new ProgressMonitorInputStream(parentComponent, "Reading " + src, new FileInputStream(src))); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); } } } 

我上面的代码工作得很好,它允许我将文件的数据从一个目录复制到另一个目录。 我的问题是,我如何创建进度条? 我可以附加到我的代码,使我的程序更加用户友好。 我尝试使用ProgressMonitorInputStream,但看起来我走错了路。 我希望有人能够给我一些帮助。

我可以想到两种方式。

摇摆工人

首先将复制代码复制到SwingWorker ,使用setProgress方法更新进度,使用属性更改侦听器监视progress属性的更改。

当progress属性更改时,您将更新UI。

此解决方案将要求您提供自己的UI

进度监视器

使用ProgressMonitorInputStream ,它带有自己的UI。

 InputStream in = new BufferedInputStream( new ProgressMonitorInputStream( parentComponent, "Reading " + fileName, new FileInputStream(fileName))); 

(从Java Docs中窃取的示例)

在这里你可以找到相同的例子。 使用Swing的Progress Monitoring API取得进展 。