Im trying to copy a file in java and move it to a new folder. This is the code i HAve been using but I always get this error \"(Access is denied) in the specified directory\". I
Edit ups messed up, second try:
You have to give the FileOutputStream a valid file name, just append the name of your file to the target path C:/users/peter/documents/foldertest2/hats/hat3
with only the folder name it will try to access the folder as if it was a file and fail.
Apache Commons IO is also another way to go, specifically FileUtils.copyFile();
it handles all the heavy lifting for you.
Use Java 7:
import static java.nio.file.StandardCopyOption.*;
Files.copy(source, target, REPLACE_EXISTING);
http://docs.oracle.com/javase/tutorial/essential/io/copy.html
Is there a way i can fix this or a better way to copy the files?
If you have the option, I would recommend you to go with Java version 7, and use the Path.copyTo method.
Copy the file located by this path to a target location. [...]
Otherwise I would recommend at least using the NIO packages and FileChannels
.
Hmm it looks like you are trying to run this on windows, should you not be using \ in your path instead of / ?
As AlexR said check your permissions on the directory you are trying to write to.
If you get this exception the access is really denied, i.e. you just do not have rights to write to the specified directory or file. So, first check it. Try for example to create the file in specified directory manually. Do you probably try to create file in somebody else' home directory? Or your java program is running as other user? What about foldertest2? Does it exist and writable? Try to copy your file there.
And the final tip. When you manage to copy the file, I'd recommend you to use IOUtils.copy()
(from jacarta commons). I use it a lot. It does almost exactly what you implemented but have to write of code one line only.