[ Java ] Code Java tải website về máy tính [ Download URL ]

Chương trình Java download URL:
- Nhập địa chỉ URL cần download
- Kết quả download được lưu tại output.htm, trong thư mục chứa Project

* Để download từ địa chỉ URL cần sử dụng 2 thư viện:
    + java.net.URL
    + java.net.URLConnection

[Code Java]

/******************************************************************************
 http://lap-trinh-may-tinh.blogspot.com/
******************************************************************************/

package download_java;
import java.util.Scanner;

public class  Download_java
{
  public static void main(String[] args) throws Exception
  {
    // Nhập địa chỉ URL cần download
      Scanner in=new Scanner(System.in);
    System.out.print("\n Nhập URL: ");
    String str_url=in.nextLine();
    // Địa chỉ URL cần download
    java.net.URL url = new java.net.URL(str_url);
    java.net.URLConnection con = url.openConnection();

    java.io.InputStream is=con.getInputStream();

    // Kết quả được lưu trên output.htm trong thư mục chứa Project
    String output_file="output.htm";
    java.io.FileOutputStream os=new java.io.FileOutputStream(output_file);

    int BUF_SIZE=1024; // KB
    byte[] buffer = new byte[BUF_SIZE];
   
    while (true)
    {
      int n = is.read(buffer);  // đọc data URL
      if (n>0) os.write(buffer,0,n);     // ghi vào file
      if (n<0) break;    // kế thúc đọc
    }
  }
}

[Download Project tại đây]

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Tài liệu: Lập trình hướng đối tượng JAVA core dành cho người mới bắt đầu học lập trình [Click để xem]

# Khoá học online: Lập trình Java trong 4 tuần [Click để xem]

Tìm kiếm nội dung khác: