Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class Main {
    /**
     * Downloads the resource with the given URL and writes it as a local file.
     *
     * @param url the URL to read from
     * @param outputFileName the name of the file to write to
     * @return the URL for the local file
     */
    public static String downloadUrlToFile(String url, String outputFileName) throws IOException {
        InputStream in = new URL(url).openStream();
        try {
            return writeStreamToFile(in, outputFileName);
        } finally {
            in.close();
        }
    }

    /**
     * Writes the contents from the given input stream to the given file.
     *
     * @param in the InputStream to read from
     * @param outputFileName the name of the file to write to
     * @return the URL for the local file
     */
    public static String writeStreamToFile(InputStream in, String outputFileName) throws IOException {
        File file = new File(outputFileName);

        // Create the parent directory.
        file.getParentFile().mkdirs();

        OutputStream out = new FileOutputStream(file);
        try {
            copy(in, out);

            // Return the URL to the output file.
            return file.toURI().toString();
        } finally {
            out.flush();
            out.close();
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        out = new BufferedOutputStream(out, 0x1000);
        in = new BufferedInputStream(in, 0x1000);

        // Copy the contents from the input stream to the output stream.
        while (true) {
            int b = in.read();
            if (b == -1) {
                break;
            }
            out.write(b);
        }
        out.flush();
    }
}