How can I download and save a file from the Internet using Java?

To download and save a file from the Internet using Java, you can use the URL and URLConnection classes from the java.net package.

Here is an example of how to download and save a file from the Internet using Java:

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class Main {
  public static void main(String[] args) {
    try {
      URL url = new URL("http://www.example.com/file.txt");
      URLConnection conn = url.openConnection();
      BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
      FileOutputStream out = new FileOutputStream("file.txt");
      byte[] buffer = new byte[1024];
      int numRead;
      long numWritten = 0;
      while ((numRead = in.read(buffer)) != -1) {
          out.write(buffer, 0, numRead);
          numWritten += numRead;
      }
      System.out.println(numWritten + " bytes written to file");
      in.close();
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

This code creates a URL object with the URL of the file to download, and then opens a connection to it using the openConnection() method. It reads the contents of the file using a BufferedInputStream and writes it to a FileOutputStream to save it to a local file.

It is important to note that this code does not handle errors such as a file not found or a connection timeout. You may want to add error handling and retry logic to your code to make it more robust.

You can also use other methods, such as the Files.copy() method from the java.nio.file package, to download and save a file from the Internet. This method can be more convenient, but it may not have as much control over the download process as using the URL and URLConnection classes.