2014-03-13 21 views
-2

嗨,我很想做一個應用程序,它從網站上下載一些東西放到桌面上。我將如何去從java應用程序下載東西,然後把它放在桌面上?

此代碼下載它,但暫時,我將如何去保存它?

繼承人我的代碼

private static void grabItem() throws ClassNotFoundException, 
     InstantiationException, IllegalAccessException, IOException, 
     UnsupportedLookAndFeelException { 
    final URL url = new URL("sampleurl"); 
    final InputStream is = url.openStream(); 
    final byte[] b = new byte[2048]; 
    int length; 
    final 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) { 
     logger.info("Unable to find file"); 
     return; 
    } 

    // set content length. 
    size = connection.getContentLength(); 
    while ((length = is.read(b)) != -1) { 
     downloaded += length; 
     progressBar.setValue((int) getProgress()); // set progress bar 
    } 
    is.close(); 
    setFrameTheme(); 

} 

感謝

+1

爲什麼地球上,你覺得有必要拋出'ClassNotFoundException'。 – Makoto

+0

下載。將該文件放入桌面目錄中。 (或者你的意思是你想讓它成爲桌面背景?) – keshlam

+0

把它放在桌面目錄 – Boolena

回答

0

你根本就不會寫入任何數據到您的計算機...但反正...

我這是怎麼下載&保存文件...它需要直接下載,但它很容易改變它以你想要的方式工作

URL url = new URL("direct link goes here"); 
URLConnection connection = url.openConnection(); 
InputStream inputstream = connection.getInputStream(); 

得到它,以節省你會那麼......

BufferedOuputStream bufferedoutputstream = new BufferedOutputStream(new FileOutputStream(new File("location to save downloaded file"))); 
byte[] buffer = new byte[1024]; 
int bytesRead = 0; 

while((bytesRead = inputstream.read(buffer))) 
{ 
    bufferedoutputstream.write(buffer, 0, bytesRead); 
} 
bufferedoutputstream.flush(); 
bufferedoutputstream.close(); 
inputstream.close(); 

應該下載&保存

+0

謝謝先生! :) – Boolena

相關問題