Java I/O How to - Save a file from the given URL using HTTPS to the given filename and return the file








Question

We would like to know how to save a file from the given URL using HTTPS to the given filename and return the file.

Answer

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/*from w w  w  . j  a v  a2  s .c om*/
import javax.net.ssl.HttpsURLConnection;


public class Main{
  /**
   * Saves a file from the given URL using HTTPS to the given filename and returns the file
   * @param link URL to file
   * @param fileName Name to save the file
   * @return The file
   * @throws IOException Thrown if any IOException occurs
   */
  public static void saveFileFromNetHTTPS(URL link, String fileName) throws IOException {
      HttpsURLConnection con = (HttpsURLConnection) link.openConnection();

      InputStream in = new BufferedInputStream(con.getInputStream());
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      byte[] buf = new byte[1024];
      int n = 0;
      while (-1 != (n = in.read(buf))) {
          out.write(buf, 0, n);
      }
      out.close();
      in.close();
      byte[] response = out.toByteArray();

      File f = new File(fileName);
      if (f.getParentFile() != null) {
          if (f.getParentFile().mkdirs()) {
              System.out.println("Created Directory Structure");
          }
      }

      FileOutputStream fos = new FileOutputStream(f);
      fos.write(response);
      fos.close();
  }
}