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.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;

public class Main {
    public static void copyFileToDir(File from, File toDir, PrintStream reportStream) {
        final File to = new File(toDir, from.getName());
        copyFile(from, to, reportStream);
    }

    public static void copyFile(File from, File toFile) {
        copyFile(from, toFile, null);
    }

    public static void copyFile(File from, File toFile, PrintStream reportStream) {
        if (reportStream != null) {
            reportStream.println("Coping file " + from.getAbsolutePath() + " to " + toFile.getAbsolutePath());
        }
        if (!from.exists()) {
            throw new IllegalArgumentException("File " + from.getPath() + " does not exist.");
        }
        if (from.isDirectory()) {
            throw new IllegalArgumentException(from.getPath() + " is a directory. Should be a file.");
        }
        try {
            final InputStream in = new FileInputStream(from);
            if (!toFile.getParentFile().exists()) {
                toFile.getParentFile().mkdirs();
            }
            if (!toFile.exists()) {
                toFile.createNewFile();
            }
            final OutputStream out = new FileOutputStream(toFile);

            final byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (final IOException e) {
            throw new RuntimeException(
                    "IO exception occured while copying file " + from.getPath() + " to " + toFile.getPath(), e);
        }

    }
}