2010-02-20 50 views
6

我想在java中編寫一個代碼,其中用戶提供一個url鏈接和程序採取url鏈接,並下載一個網頁,因爲它和保存在特定的位置..同樣另存爲...選項在網頁上可用。通過使用Java代碼傳遞URL下載文件

請任何人可以幫助我

在此先感謝

+1

你可以說你迄今爲止做了什麼嗎?你卡在哪一點? – 2010-02-20 13:04:01

回答

9

//樣品網址:http://www.novell.com/coolsolutions/tools/downloads/ntradping.zip

import java.io.*; 
import java.net.*; 


public class UrlDownload { 
    final static int size = 1024; 

    public static void fileUrl(String fAddress, String localFileName, String destinationDir) { 
     OutputStream outStream = null; 
     URLConnection uCon = null; 

     InputStream is = null; 
     try { 
      URL url; 
      byte[] buf; 
      int byteRead, byteWritten = 0; 
      url = new URL(fAddress); 
      outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName)); 

      uCon = url.openConnection(); 
      is = uCon.getInputStream(); 
      buf = new byte[size]; 
      while ((byteRead = is.read(buf)) != -1) { 
       outStream.write(buf, 0, byteRead); 
       byteWritten += byteRead; 
      } 
      System.out.println("Downloaded Successfully."); 
      System.out.println("File name:\"" + localFileName + "\"\nNo ofbytes :" + byteWritten); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
       outStream.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    public static void fileDownload(String fAddress, String destinationDir) { 
     int slashIndex = fAddress.lastIndexOf('/'); 
     int periodIndex = fAddress.lastIndexOf('.'); 

     String fileName = fAddress.substring(slashIndex + 1); 

     if (periodIndex >= 1 && slashIndex >= 0 && slashIndex < fAddress.length() - 1) { 
      fileUrl(fAddress, fileName, destinationDir); 
     } else { 
      System.err.println("path or file name."); 
     } 
    } 

    public static void main(String[] args) { 
     if (args.length == 2) { 
      for (int i = 1; i < args.length; i++) { 
       fileDownload(args[i], args[0]); 
      } 
     } else { 
     } 
    } 
} 

據工作充分。

+0

請檢查你的代碼,也許參數'fileDownload(args [i],args [0]);'應該被交換。 – Daniele 2017-01-24 13:56:31