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.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    /**
     * Copy a file from src to dst path.
     */
    public static boolean fileCopy(String srcFilepath, String dstFilepath) {
        return fileCopy(new File(srcFilepath), new File(dstFilepath));
    }

    public static boolean fileCopy(File srcFile, File dstFile) {
        int length = 1048891;
        FileChannel inC = null;
        FileChannel outC = null;
        try {
            FileInputStream in = new FileInputStream(srcFile);
            FileOutputStream out = new FileOutputStream(dstFile);
            inC = in.getChannel();
            outC = out.getChannel();
            ByteBuffer b = null;
            while (inC.position() < inC.size()) {
                if ((inC.size() - inC.position()) < length) {
                    length = (int) (inC.size() - inC.position());
                } else {
                    length = 1048891;
                }
                b = ByteBuffer.allocateDirect(length);
                inC.read(b);
                b.flip();
                outC.write(b);
                outC.force(false);
            }

            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (inC != null && inC.isOpen()) {
                    inC.close();
                }
                if (outC != null && outC.isOpen()) {
                    outC.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}