Here you can find the source of getFile(String host, String savePath)
Parameter | Description |
---|---|
host | a parameter |
savePath | a parameter |
public static String getFile(String host, String savePath)
//package com.java2s; //License from project: Open Source License import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class Main { /**// ww w . ja v a 2s . c om * Get a file from a host uri, and save it into the save path * @param host * @param savePath * @return */ public static String getFile(String host, String savePath) { InputStream input = null; FileOutputStream writeFile = null; String path = new String(); try { URL url = new URL(host); URLConnection connection = url.openConnection(); int fileLength = connection.getContentLength(); if (fileLength == -1) { System.out.println("Invalide URL or file."); return null; } input = connection.getInputStream(); String fileName = url.getFile().substring(url.getFile().lastIndexOf('/') + 1); path = savePath + "/" + fileName; writeFile = new FileOutputStream(path); byte[] buffer = new byte[1024]; int read; while ((read = input.read(buffer)) > 0) writeFile.write(buffer, 0, read); writeFile.flush(); } catch (IOException e) { System.out.println("Error while trying to download the file."); e.printStackTrace(); } finally { try { writeFile.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } } return path; } }