簡體   English   中英

文件傳輸時如何創建進度條

[英]How create progress bar while file transferring

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,但看來我走錯了路。

我可以想到兩種方式。

秋千工人

首先,使用setProgress方法將代碼包裝到SwingWorker ,然后使用setProgress方法更新進度,並使用屬性更改偵聽器監視對progress屬性的更改。

當progress屬性更改時,您將隨后更新UI。

此解決方案將需要您提供自己的UI

進度監控器

使用它自己的UI附帶的ProgressMonitorInputStream

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

(示例從Java Docs被盜)

在這里您可以找到相同的示例。 使用Swing的進度監控API取得進展

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM