Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    private static void downloadResource(String from, String to) {
        OutputStream outputStream = null;
        BufferedInputStream inputStream = null;
        HttpURLConnection connection = null;
        URL url;
        byte[] buffer = new byte[1024];

        try {
            url = new URL(from);

            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.connect();
            outputStream = new FileOutputStream(to);

            inputStream = new BufferedInputStream(url.openStream());
            int read;

            while ((read = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, read);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null)
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            if (inputStream != null)
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            if (connection != null)
                connection.disconnect();
        }
    }
}