2010-02-20 38 views
6

Tôi đang cố gắng viết mã bằng java trong đó người dùng cung cấp liên kết url và chương trình có liên kết url và tải xuống trang web như nó đang lưu và lưu tại vị trí cụ thể..same as lưu dưới dạng ... tùy chọn có sẵn trên trang web.Tải xuống tệp bằng cách chuyển URL bằng cách sử dụng mã java

Hãy thể ai giúp tôi

Cảm ơn trước

+1

Bạn có thể nói những gì bạn đã làm cho đến nay không? Bạn bị kẹt ở điểm nào? –

Trả lời

5

Bạn có thể sử dụng URL Java API để có được thêm một input stream trên URL sau đó đọc từ nó và viết thông qua dòng sản lượng trên một tập tin.

thấy read data from url, Write to file

1

Có một cái nhìn tại HtmlParser. Nó có một số tính năng sẽ giúp bạn trích xuất tài nguyên từ một trang web.

9

// URL mẫu: 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 { 
     } 
    } 
} 

Nó đang làm việc đầy đủ.

+0

Vui lòng che mã của bạn, có thể là arg trong câu lệnh 'fileDownload (args [i], args [0]);' sẽ được đổi chỗ. – Daniele

Các vấn đề liên quan