Copy file from one folder to another in Java
Asked Answered
M

3

5

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?

Mikael answered 21/1, 2014 at 11:2 Comment(6)
Do you get any errors?Gulp
You can find the answer by follow the below mention link [Copy file from one directory to another][1] [1]: #1146653Shibboleth
Didn't you invert source and destination ?Cyaneous
no errors but file is not copyingMikael
@X.L.Ant : I think he did invert it. Syntax FileUtils.copyFileToDirectory(srcFile, destDir);Horsehair
You may have a permissions issueKremlin
P
6

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

Polymer answered 21/1, 2014 at 11:7 Comment(0)
H
3

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);
Heterography answered 21/1, 2014 at 11:51 Comment(0)
D
2

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);
Drumm answered 21/1, 2014 at 11:14 Comment(2)
can i know value of newPathDrumm
actually my program will generate a folder which containing some files i just want to copy chart.js with thatMikael

© 2022 - 2024 — McMap. All rights reserved.