2012-02-23 42 views
0

我有以下代碼。我無法讓它工作。我不得不提到URL是重定向的。我的意思是url = http://www.thissite.com並重定向到http://www.othersite.com。但我想讓它與最初的url一起工作。連接JProgressBar與下載過程

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 ;) 
     } 
    } 
} 
+2

我不知道如何解決您的重定向問題,但JProgressBar不起作用?您是否確定將此代碼從EDT中撥出?您需要確保您在EDT上調用JProgressBar的'setValue(...)'方法***。 – 2012-02-23 20:36:32

+0

我打電話下載(「http://www.site.com」,「file.txt」,jProgressBar1)l開始下載並且進度條保留填充狀態 – 2012-02-23 20:43:15

回答

3
+0

不要忘記看看教程,例如http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/ProgressBarDemoProject/src/components/ProgressBarDemo.java給出一個很好的簡單例子,說明如何使用SwingWorker在另一個線程中運行ProgressBar。 – 2012-02-23 20:49:15

+0

我檢查過了.....我在哪裏添加我的下載代碼?在doinbackground裏面?或其他地方? – 2012-02-23 21:00:12

+1

@JessyJameson:絕對是在SwingWorker的'doInBackground'爲你提供的後臺線程中完成的。 – 2012-02-23 21:26:30