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". Is there a way i can fix this or a better way to copy the files? thanks
try{
File f1 = new File(fpath);
File f2 = new File("C:/users/peter/documents/foldertest2/hats");
InputStream in = new FileInputStream(f1);
//For Append the file.
//OutputStream out = new FileOutputStream(f2,true);
//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
UPDATE: I checked the folder permissions and they are all open for all users and mine
Another common way to copy a file with Java is by using the commons-io library. The latest version can be downloaded from Maven Central. Then, to copy a file we just need to use the copyFile() method defined in the FileUtils class. The method takes a source and a target file.
The copy() method of Java Collections class copies all of the elements from one list into another list. In this method, the size of the destination list must be greater than or equal to the size of the source list.
Apache Commons IO is also another way to go, specifically FileUtils.copyFile();
it handles all the heavy lifting for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With