Java Host Name Get getFile(String host, String savePath)

Here you can find the source of getFile(String host, String savePath)

Description

Get a file from a host uri, and save it into the save path

License

Open Source License

Parameter

Parameter Description
host a parameter
savePath a parameter

Declaration

public static String getFile(String host, String savePath) 

Method Source Code

//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;
    }
}

Related

  1. getCanonicalHostName()
  2. getCanonicalHostName()
  3. getCasServerHostName()
  4. getCurrentHost()
  5. getDefaultHostName()
  6. getFullHostname()
  7. getFullyQualifiedDomainName(String unqualifiedHostname)
  8. getFullyQualifiedHostName()
  9. getHost()