Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy file in java

Tags:

java

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

like image 923
Peter Avatar asked Feb 15 '11 12:02

Peter


People also ask

How do you copy a file in Java?

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.

What is copy () in Java?

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.


1 Answers

Apache Commons IO is also another way to go, specifically FileUtils.copyFile(); it handles all the heavy lifting for you.

like image 64
Dead Programmer Avatar answered Sep 28 '22 01:09

Dead Programmer