Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Copy file to another directory using FileUtils and copyFileToDirectory - doesn't work -?

I would like to copy a file from one directory to another using Java and the FileUtils classes of apache org commons.

I wrote up a quick java program to test on my local system. Here is the code. The file exists, but the copying of the file to another directory isn't working. What am I missing? Is there some improper syntax somewhere?

import org.apache.commons.io.FileUtils;
import java.io.File;

class MoveFile {

    public static void main(String[] args) {
        MoveFile myobj = new MoveFile();
        myobj.moveTheFile();
    }

    public void moveTheFile () {
        try {
            File destDir = new File("C:\\Folder1\\temp2");
            File srcFile = new File("C:\\Folder1\\temp\\card.png");
            FileUtils.copyFileToDirectory(srcFile, destDir);
        } catch(Exception e) {
        }
    }

}
like image 810
katura Avatar asked Feb 10 '12 21:02

katura


People also ask

How do you copy a file from a directory to another directory in Java?

copyFile (File Source, File Destination) This method copies a file to a new location preserving file timestamp. It also copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist.

How to duplicate a file using Java?

Another common way to copy a file with Java is by using the commons-io library. The latest version can be downloaded from Maven Central. Then, to copy a file we just need to use the copyFile() method defined in the FileUtils class. The method takes a source and a target file.


1 Answers

Replicated your error and it only fails when the program does not have permission to write on destination folder. Even catching a throwable and printing stacktrace shows no info and the method is quite silent... if the folder does not exist, the method creates it so disregard that possible correction.

Check write permissions in destination folder

like image 125
Alfabravo Avatar answered Sep 20 '22 09:09

Alfabravo