在更新JProgressBar的同时下载文件 [英] Download a file while also updating a JProgressBar

查看:103
本文介绍了在更新JProgressBar的同时下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过不同方法的音调来让它工作,但是它们不能与进度条一起工作,或者不按照我想要的方式工作。

I have tried tones of different methods to get this to work but they either don't work with a progress bar or don't work the way I would like it to.

我已经创建了一个带有进度条的新窗口,需要创建一个方法,允许我下载一个文件,同时更新一个 JProgressBar 。有一个Apache Commons方法非常容易用于下载文件,但它似乎与 JProgressBar 的兼容。

I have already created a new window with a progress bar and need to create a method which would allow me to download a file while also updating a JProgressBar. There is an Apache Commons method that is extremely easy to use for downloading files but it doesn't seem to be compatible with JProgressBar's.

我在另一个线程中运行时也遇到麻烦, SwingUtilities.invokeLater 似乎没有更新到进度条,但它的运行方式我可以把它打印到控制台。我甚至尝试了 progressBar.repaint()方法。

I have also had trouble when running this in another thread, SwingUtilities.invokeLater doesn't seem to update to progress bar, but it does run as I can get it to print to the console. I have even tried the progressBar.repaint() method.

所以我想要的是一种可以下载文件,同时更新 JProgressBar 以反映下载的状态。

So what I would like is a method that can download a file while also updating a JProgressBar to reflect the status of the download.

提前感谢!
Keir

Thanks in advance! Keir

推荐答案

根据这篇文章,我可以建议你要写一个下载类,可以轻松更新进度条。

Based on this article, I can suggest you to write a Download class, which can update a progress bar easily.

这是下载类:

import java.io.*;
import java.net.*;
import java.util.*;

// This class downloads a file from a URL.
class Download extends Observable implements Runnable {

// Max size of download buffer.
private static final int MAX_BUFFER_SIZE = 1024;

// These are the status names.
public static final String STATUSES[] = {"Downloading",
"Paused", "Complete", "Cancelled", "Error"};

// These are the status codes.
public static final int DOWNLOADING = 0;
public static final int PAUSED = 1;
public static final int COMPLETE = 2;
public static final int CANCELLED = 3;
public static final int ERROR = 4;

private URL url; // download URL
private int size; // size of download in bytes
private int downloaded; // number of bytes downloaded
private int status; // current status of download

// Constructor for Download.
public Download(URL url) {
    this.url = url;
    size = -1;
    downloaded = 0;
    status = DOWNLOADING;

    // Begin the download.
    download();
}

// Get this download's URL.
public String getUrl() {
    return url.toString();
}

// Get this download's size.
public int getSize() {
    return size;
}

// Get this download's progress.
public float getProgress() {
    return ((float) downloaded / size) * 100;
}

// Get this download's status.
public int getStatus() {
    return status;
}

// Pause this download.
public void pause() {
    status = PAUSED;
    stateChanged();
}

// Resume this download.
public void resume() {
    status = DOWNLOADING;
    stateChanged();
    download();
}

// Cancel this download.
public void cancel() {
    status = CANCELLED;
    stateChanged();
}

// Mark this download as having an error.
private void error() {
    status = ERROR;
    stateChanged();
}

// Start or resume downloading.
private void download() {
    Thread thread = new Thread(this);
    thread.start();
}

// Get file name portion of URL.
private String getFileName(URL url) {
    String fileName = url.getFile();
    return fileName.substring(fileName.lastIndexOf('/') + 1);
}

// Download file.
public void run() {
    RandomAccessFile file = null;
    InputStream stream = null;

    try {
        // Open connection to URL.
        HttpURLConnection connection =
                (HttpURLConnection) url.openConnection();

        // Specify what portion of file to download.
        connection.setRequestProperty("Range",
                "bytes=" + downloaded + "-");

        // Connect to server.
        connection.connect();

        // Make sure response code is in the 200 range.
        if (connection.getResponseCode() / 100 != 2) {
            error();
        }

        // Check for valid content length.
        int contentLength = connection.getContentLength();
        if (contentLength < 1) {
            error();
        }

  /* Set the size for this download if it
     hasn't been already set. */
        if (size == -1) {
            size = contentLength;
            stateChanged();
        }

        // Open file and seek to the end of it.
        file = new RandomAccessFile(getFileName(url), "rw");
        file.seek(downloaded);

        stream = connection.getInputStream();
        while (status == DOWNLOADING) {
    /* Size buffer according to how much of the
       file is left to download. */
            byte buffer[];
            if (size - downloaded > MAX_BUFFER_SIZE) {
                buffer = new byte[MAX_BUFFER_SIZE];
            } else {
                buffer = new byte[size - downloaded];
            }

            // Read from server into buffer.
            int read = stream.read(buffer);
            if (read == -1)
                break;

            // Write buffer to file.
            file.write(buffer, 0, read);
            downloaded += read;
            stateChanged();
        }

  /* Change status to complete if this point was
     reached because downloading has finished. */
        if (status == DOWNLOADING) {
            status = COMPLETE;
            stateChanged();
        }
    } catch (Exception e) {
        error();
    } finally {
        // Close file.
        if (file != null) {
            try {
                file.close();
            } catch (Exception e) {}
        }

        // Close connection to server.
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {}
        }
    }
}

// Notify observers that this download's status has changed.
private void stateChanged() {
    setChanged();
    notifyObservers();
}
}

如您所见,这个下载类有一些特定的字段,如 size 已下载

As you can see, this Download class has got some specific fields like size and downloaded.

在某些其他方法中,您可以写:

In some other method you could write:

JProgressBar j = new JProgressBar(0,download.getSize());

此后,您可以启动一个新的线程 ,它会以一定的间隔更新您的进度条,例如每10 ms,

After this you could start a new Thread, which does update your progress bar at a certain interval, like every 10 ms, with

j.setValue(download.getDownloaded());

希望这可以帮助你。

这篇关于在更新JProgressBar的同时下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆