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 {
    /**
     * Moves a file to another location.
     */
    public static void move(File from, File to) {
        if (!from.renameTo(to)) {
            copyFile(from, to);
            if (!from.delete()) {
                if (!to.delete()) {
                    throw new RuntimeException("Unable to delete " + to);
                }
                throw new RuntimeException("Unable to delete " + from);
            }
        }
    }

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

    }

    public static void delete(File file) {
        if (!file.delete()) {
            throw new RuntimeException("File " + file.getAbsolutePath() + " can't be deleted.");
        }
    }
}