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

3

12

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) {
        }
    }

}
Lxx answered 10/2, 2012 at 21:58 Comment(4)
what does that mean isn't working? any errors? data not copied?Flyspeck
does the initial file exist? does the destination directory exist? what does the exception say when it fails?Putrid
The file and directory both exist. There are no exceptions logged.Lxx
Amazing, This question helps me to solve my answer.Marchall
P
10

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

Prentice answered 10/2, 2012 at 22:23 Comment(1)
I overlooked one error in the destination directory variable - it should've been Folder1/temp/temp2. The directory had 'read only' permissions, so I changed that. Now the test program works. Thank you for your help.Lxx
I
3

It is never a good idea to do swallow exceptions. Do an e.printstacktrace() in your exception handling mechanism for more information. Since you did not specify any other information, first thing that comes to mind is that if you are using Windows vista or later, usually it will ask you for administrator consent when placing items directly in your C:\ directory.

To see if this is the problem, I would recommend you test this out in other directories such as My Documents or else, disable the UAC.

Iroquois answered 10/2, 2012 at 22:5 Comment(0)
R
1

Do

destDir.mkdirs();

or

FileUtils.forceMkdir(destDir);

to create the directory temp2 first.

Rianon answered 10/2, 2012 at 22:22 Comment(1)
The temp2 directory is already created on the system so making the directory would not be necessary.Lxx

© 2022 - 2024 — McMap. All rights reserved.