java - 将 JProgressBar 与下载进程连接

标签 java swing download jprogressbar

我有以下代码。我无法让它发挥作用。

我必须提到 URL 正在重定向。我的意思是 url = http://www.thissite.com 并重定向到 http://www.othersite.com。但我想让它与初始 url 一起工作。

 public void download(String address, String localFileName, JProgressBar progress ) {
    OutputStream out = null;
    URLConnection conn = null;
    InputStream in = null;

    try {

          URL url = new URL(address);



        // Open an output stream to the destination file on our local filesystem
        out = new BufferedOutputStream(new FileOutputStream("/MusicDownloads/"+localFileName));
        conn = url.openConnection();

        in = conn.getInputStream();

        int length = conn.getContentLength(); //find out how long the file is, any good webserver should provide this info
         int current = 0;
          progress.setMaximum(length); //we're going to get this many bytes
          progress.setValue(0); //we've gotten 0 bytes so far

        // Get the data
        byte[] buffer = new byte[1024];
        int numRead = 0;

        while ((numRead = in.read(buffer)) != -1) {
            current=0;
            out.write(buffer, current, numRead);

              current += numRead; //we've progressed a little so update current

            progress.setValue(current); //tell progress how far we are


        }
        // Done! Just clean up and get out
    } catch (Exception exception) {
        exception.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
            // Shouldn't happen, maybe add some logging here if you are not
            // fooling around ;)
        }
    }
}

最佳答案

使用 ProgressMonitorInputStream相反。

关于java - 将 JProgressBar 与下载进程连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9420778/

相关文章:

java - 发布后 Android 排行榜不工作显示 RESULT_APP_MISCONFIGURED 错误

java - java中的scanner.useDelimiter ("\n\n")

java - isAnonymous() 和 isAuthenticated() 都返回 false

python - 使用 python 下载部分 youtube 视频

Android/Java : HttpURLConnection doesn't return headers of redirected file (e. g。在 S3)

php - CakePHP:使用 $this->response->file() 时如何设置文件名

Java解析字符串输入

java - 无法让 Darkula 在 Netbeans 中以外观和感觉工作

java - DocumentListener 会减慢 Document.setCharacterAttributes 方法的速度吗?

java - 如何隐藏jSlider的旋钮?