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








Question

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

Answer

//from w w w  .ja  va  2s .  com
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;


public class Main{
  /**
   * Saves a file from the given URL 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 File saveFileFromNet(URL link, String fileName) throws IOException {
      InputStream in = new BufferedInputStream(link.openStream());
      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 file = new File(fileName);
      if (!file.exists()) {
          if (file.getParentFile() != null) {
              file.getParentFile().mkdirs();
          }
          file.createNewFile();
      }
      FileOutputStream fos = new FileOutputStream(file);
      fos.write(response);
      fos.close();

      return new File(fileName);
  }
}