Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
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 {
    /** Copy files or folders */
    public static boolean copyFiles(File srcFile, File dstFile) {
        boolean ret = true;

        if (srcFile.getParent().equals(dstFile)) {
            return false;
        }

        if (srcFile.isDirectory()) {
            if (dstFile.getPath().indexOf(srcFile.getPath()) == 0) {
                return false;
            } else {
                if (copyDir(srcFile, dstFile) == false) {
                    return false;
                }
            }
        } else {
            ret = copyFile(srcFile, dstFile);
        }

        return ret;
    }

    /** Copy folders */
    private static boolean copyDir(File srcDir, File dstDir) {
        if (dstDir.exists()) {
            if (dstDir.isDirectory() == false) {
                return false;
            }
        } else {
            if (dstDir.mkdirs() == false) {
                return false;
            }
        }
        if (dstDir.canWrite() == false) {
            return false;
        }

        File[] files = srcDir.listFiles();
        if (files == null) {
            return false;
        }

        for (int i = 0; i < files.length; i++) {
            File dstFile = new File(dstDir, files[i].getName());
            if (files[i].isDirectory()) {
                copyDir(files[i], dstFile);
            } else {
                copyFile(files[i], dstFile);
            }
        }

        return true;
    }

    /** Copy binary file */
    public static boolean copyFile(File srcFile, File dstFile) {
        try {
            InputStream in = new FileInputStream(srcFile);
            if (dstFile.exists()) {
                dstFile.delete();
            }

            OutputStream out = new FileOutputStream(dstFile);
            try {
                int cnt;
                byte[] buf = new byte[4096];
                while ((cnt = in.read(buf)) >= 0) {
                    out.write(buf, 0, cnt);
                }
            } finally {
                out.close();
                in.close();
            }
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}