2012-02-23 4 views
0

私は以下のコードを持っています。私はそれを働かせることはできません。ダウンロードプロセスで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 ;) 
     } 
    } 
} 
+2

リダイレクトの問題を解決する方法はわかりませんが、JProgressBarは機能しません。このコードをEDTから呼び出すことを確認していますか? *** EDTのJProgressBarのsetValue(...)メソッド***を呼び出す必要があります。 –

+0

ダウンロードを開始するにはdownload( "http://www.site.com"、 "file.txt"、jProgressBar1)を呼び出しています。プログレスバーは固定されたままです –

答えて

3

代わりにProgressMonitorInputStreamを使用してください。

+0

チュートリアルなどを見ているのを忘れないでくださいhttp://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/ProgressBarDemoProject/src/components/ProgressBarDemo.java give他のスレッドでProgressBarを実行するためのSwingWorkerの使い方の良い例です。 –

+0

私はそれを確認しました.....私はダウンロードコードをどこに追加する必要がありますか?ドゥーバックグラウンドの中に?または他の場所? –

+1

@JessyJameson:間違いなくSwingWorkerのdoInBackgroundが提供するバックグラウンドスレッドで実行します。 –

関連する問題