Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy file from one folder to another in Java

I am trying to copy a file from one folder to another folder.

Here's what I have got in my code:

public static void copyFile(String path) throws IOException{
   newPath = path;    
   File destination = new File ("E:/QA/chart.js"); 
   FileUtils.copyFile(destination, new File(newPath));      
}

But it is not copying the desired file to its location. What is required, its copy chart.js from E drive and copy to the newPath variable location.

Is there some other way to copy files from one place to another?

like image 342
Atal Shrivastava Avatar asked Jan 21 '14 11:01

Atal Shrivastava


Video Answer


3 Answers

You can use standard java.nio.file.Files.copy(Path source, Path target, CopyOption... options)

like image 57
Evgeniy Dorofeev Avatar answered Oct 25 '22 07:10

Evgeniy Dorofeev


You can use this

Path FROM = Paths.get(Your Source file complete path);
Path TO = Paths.get(Destination complete path);
CopyOption[] options = new CopyOption[]{
  StandardCopyOption.REPLACE_EXISTING,
  StandardCopyOption.COPY_ATTRIBUTES
}; 
java.nio.file.Files.copy(FROM, TO, options);
like image 31
ravibagul91 Avatar answered Oct 25 '22 06:10

ravibagul91


Try this.

FileUtils.copyFile(src, dest)

this is happening in copy. so this point of view File src = new File ("E:/QA/chart.js"); assume src file existing one. Then you create a new destination file like this

File dest = new File(newPath);
if(!dest.exists())
  dest.createNewFile();

Then you can copy

FileUtils.copyFile(src,dest);
like image 36
subash Avatar answered Oct 25 '22 07:10

subash