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.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    /**
     * Copies the contents of one local file to another local file.
     *
     * @param inputFileName the name of the file to read to
     * @param outputFileName the name of the file to write to
     * @return the URL for the local file
     */
    public static String copyFile(String inputFileName, String outputFileName) throws IOException {
        InputStream in = new FileInputStream(inputFileName);
        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();
    }
}