2010-02-20 12 views
6

Sto provando a scrivere un codice in java in cui l'utente fornisce un collegamento url e il programma prende il link url e scarica una pagina web così com'è e salva in una particolare posizione ... come salva come ... opzione disponibile sulla pagina web.Scarica il file passando l'URL utilizzando il codice java

Si prega di qualcuno può aiutarmi

Grazie in anticipo

+1

Puoi dire quello che hai fatto finora? A che punto sei bloccato? –

risposta

5

È possibile utilizzare API Java URL per ottenere un flusso di input sull'URL poi leggere il da esso e scrivere attraverso il flusso di output su un file.

vedere read data from url, Write to file

1

Date un'occhiata al HtmlParser. Ha alcune funzionalità che ti aiuteranno a estrarre risorse da una pagina web.

9

// URL del campione: 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 { 
     } 
    } 
} 

Si sta lavorando completamente.

+0

Prego che il tuo codice, forse gli argomenti nell'istruzione 'fileDownload (args [i], args [0]);' dovrebbe essere scambiato. – Daniele