Here you can find the source of downloadFile(File parent, String prefix, String suffix, URL url)
Parameter | Description |
---|---|
parent | parent directory, may be <code>null</code> then use 'java.io.tmpdir' |
prefix | prefix of temporary file name, may not be <code>null</code> and must be at least three characters long |
suffix | suffix of temporary file name, may be <code>null</code> |
url | URL for download |
Parameter | Description |
---|
public static File downloadFile(File parent, String prefix, String suffix, URL url) throws IOException
//package com.java2s; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class Main { /**/*from w w w . ja v a 2s. c o m*/ * Download file. * * @param parent * parent directory, may be <code>null</code> then use 'java.io.tmpdir' * @param prefix * prefix of temporary file name, may not be <code>null</code> and must be at least three characters long * @param suffix * suffix of temporary file name, may be <code>null</code> * @param url * URL for download * @return downloaded file * @throws java.io.IOException * if any i/o error occurs */ public static File downloadFile(File parent, String prefix, String suffix, URL url) throws IOException { File file = File.createTempFile(prefix, suffix, parent); URLConnection conn = null; final String protocol = url.getProtocol().toLowerCase(); try { conn = url.openConnection(); if ("http".equals(protocol) || "https".equals(protocol)) { HttpURLConnection http = (HttpURLConnection) conn; http.setInstanceFollowRedirects(false); http.setRequestMethod("GET"); } try (InputStream input = conn.getInputStream(); FileOutputStream fOutput = new FileOutputStream(file)) { byte[] b = new byte[8192]; int r; while ((r = input.read(b)) != -1) { fOutput.write(b, 0, r); } } } finally { if (conn != null && ("http".equals(protocol) || "https".equals(protocol))) { ((HttpURLConnection) conn).disconnect(); } } return file; } }