Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a file to a directory in Java 7

Tags:

java

nio

I'm trying to copy a number of files to an output directory in Java 7 using Path and Files. This doesn't work:

Files.copy(Paths.get("/my/file.txt"), Paths.get("/my/output/directory/");

It generates a "directory not empty" error.

Yes, I could write code to name the output file directly, or use Guava, but I'm trying to do it the simplest way using the new Java 7 nio classes.

like image 329
ccleve Avatar asked Oct 30 '13 21:10

ccleve


3 Answers

The command appears to be attempting to replace the directory itself. Try specifying the filename in the target directory

Files.copy(Paths.get("/my/file.txt"), Paths.get("/my/output/directory/file.txt"));
like image 103
Reimeus Avatar answered Nov 02 '22 05:11

Reimeus


The easiest way:

Path file = /* path to source file */
Path to = /* path to destination directory */
Files.copy(file, to.resolve(file.getFileName()));
like image 24
W vd L Avatar answered Nov 02 '22 04:11

W vd L


From docs Java 7:

copy(Path source, Path target, CopyOption... options)

Copy a file to a target file.

So you must specify destination file.

I have a large number of files

You can get file name by splitting source path and append to destination folder.

like image 28
Maxim Shoustin Avatar answered Nov 02 '22 04:11

Maxim Shoustin