How to copy a file to a directory in Java 7

I am trying to copy multiple files to the output directory in Java 7 using Path and Files. This does not 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 directly name the output file, or use Guava, but I'm trying to do this in the easiest way using the new Java 7 nio classes.

+4
source share
3 answers

The easiest way:

 Path file = /* path to source file */ Path to = /* path to destination directory */ Files.copy(file, to.resolve(file.getFileName())); 
+5
source

From Java 7 docs:

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

Copy file to target file .

So you must specify the destination file.

I have a large number of files

You can get the file name by dividing the source path and adding to the destination folder.

+3
source

A command appears trying to replace the directory itself. Try specifying the file name in the destination directory

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

Source: https://habr.com/ru/post/977547/


All Articles