Java FileChannel Copy copyFileLocking(File copyFrom, File copyTo)

Here you can find the source of copyFileLocking(File copyFrom, File copyTo)

Description

copy File Locking

License

Open Source License

Declaration

public static boolean copyFileLocking(File copyFrom, File copyTo) throws FileNotFoundException, IOException 

Method Source Code


//package com.java2s;
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.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class Main {

    public static boolean copyFileLocking(File copyFrom, File copyTo) throws FileNotFoundException, IOException {
        if ((!(copyFrom.exists())) || (copyTo == null)) {
            return false;
        }//from w  ww.ja v  a 2  s .  c  o m
        byte[] arrayOfByte = new byte[4096];
        FileOutputStream fileOutput = new FileOutputStream(copyTo, true);
        try {
            FileChannel channel = fileOutput.getChannel();
            FileLock fileLock = channel.tryLock();
            if (fileLock != null) {
                channel.truncate(0L);
                BufferedInputStream input = new BufferedInputStream(new FileInputStream(copyFrom));
                BufferedOutputStream output = new BufferedOutputStream(fileOutput);
                try {
                    int i;
                    while ((i = input.read(arrayOfByte, 0, arrayOfByte.length)) != -1) {
                        output.write(arrayOfByte, 0, i);
                    }
                    output.flush();
                    fileLock.release();
                } catch (Exception ex) {
                    throw new RuntimeException("copyFileLocking ERR : " + ex.getMessage(), ex);
                } finally {
                    output.close();
                    input.close();
                }
                return true;
            }
        } catch (Exception ex) {
            throw new RuntimeException("copyFileLocking ERR : " + ex.getMessage(), ex);
        } finally {
            fileOutput.close();
        }
        throw new IOException("Unable to acquire file lock for " + copyTo);
    }
}

Related

  1. copyFile(String srcFileName, String desFileName)
  2. copyFile(String srcPath, String destPath)
  3. copyFileByChannel(String srcFileName, String dstFileName)
  4. copyFileContent(final String sourcePath, final String targetPath)
  5. copyFileIntoProjectFolder(String projectName, File file)
  6. copyFileNIO(File src, File dest)
  7. copyFileNio(File src, File dst)
  8. copyFileOrDirectory(File source, File destination, boolean flag)
  9. copyFiles(File originalFile, File destinationFile)