首页javawriteJava I/O - 如何使用HTTPS将给定URL中的文件保存到给定的文件名,并返回文件

Java I/O - 如何使用HTTPS将给定URL中的文件保存到给定的文件名,并返回文件

我们想知道如何使用HTTPS将给定URL中的文件保存到给定的文件名,并返回文件。
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;

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();
  }
}