Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    public static boolean copyFile(String src, String dst, boolean overwrite) {
        File dstf = new File(dst);
        File srcf = new File(src);

        //  if we can't overwrite, error
        if (!overwrite && dstf.exists())
            return false;

        //  if we must overwrite but can't delete, error
        if (overwrite && dstf.exists()) {
            boolean deleted = deleteFile(dst);
            if (!deleted)
                return false;
        }

        //  now copy
        copyWithStreams(srcf, dstf);

        return true;
    }

    public static boolean deleteFile(String path) {
        try {
            File fileToDelete = new File(path);
            if (fileToDelete.exists()) {
                fileToDelete.delete();
            }
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    private static void copyWithStreams(File aSourceFile, File aTargetFile) {
        InputStream inStream = null;
        OutputStream outStream = null;

        try {
            try {
                byte[] bucket = new byte[32 * 1024];
                inStream = new BufferedInputStream(new FileInputStream(aSourceFile));
                outStream = new BufferedOutputStream(new FileOutputStream(aTargetFile, false));
                int bytesRead = 0;
                while (bytesRead != -1) {
                    bytesRead = inStream.read(bucket); //-1, 0, or more
                    if (bytesRead > 0) {
                        outStream.write(bucket, 0, bytesRead);
                    }
                }
            } finally {
                if (inStream != null)
                    inStream.close();
                if (outStream != null)
                    outStream.close();
            }
        } catch (FileNotFoundException ex) {
        } catch (IOException ex) {
        }
    }
}