簡體   English   中英

將JProgressBar與下載過程連接

[英]Connect JProgressBar with download process

我有下面的代碼。 我不能使它工作。

我不得不提到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 ;)
        }
    }
}

暫無
暫無

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

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