0

How to move files and directories into another directory in Java? I am using this technique to copy but I need to move:

    File srcFile = new File(file.getCanonicalPath());
    String destinationpt = "/home/dev702/Desktop/svn-tempfiles";

    copyFiles(srcFile, new File(destinationpt+File.separator+srcFile.getName()));
Basilevs
  • 22,440
  • 15
  • 57
  • 102
Prasath Bala
  • 698
  • 1
  • 7
  • 12
  • 3
    possible duplicate of [Move / Copy File Operations in Java](http://stackoverflow.com/questions/300559/move-copy-file-operations-in-java) – Eel Lee Feb 25 '14 at 12:31
  • 1
    @EelLee Some of the answers in there are quite outdated. – assylias Feb 25 '14 at 12:45

3 Answers3

3

You can try this:

srcFile.renameTo(new File("C:\\folderB\\" + srcFile.getName()));
Sathesh
  • 378
  • 1
  • 4
  • 13
2

Have you read this "http://java.about.com/od/InputOutput/a/Deleting-Copying-And-Moving-Files.htm "

    Files.move(original, destination, StandardCopyOption.REPLACE_EXISTING)

move the files to destination.

If you want to move directory Use this

     File dir = new File("FILEPATH");
     if(dir.isDirectory()) {
     File[] files = dir.listFiles();
     for(int i = 0; i < files.length; i++) {
       //move files[i]
     }

}

saravanakumar
  • 1,747
  • 4
  • 20
  • 38
1

Java.io.File does not contains any ready make move file method, but you can workaround with the following two alternatives :

  1. File.renameTo()

  2. Copy to new file and delete the original file.

    public class MoveFileExample 
    {
      public static void main(String[] args)
      { 
      try{
    
       File afile =new File("C:\\folderA\\Afile.txt");
    
       if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
        System.out.println("File is moved successful!");
       }else{
        System.out.println("File is failed to move!");
       }
    
    }catch(Exception e){
        e.printStackTrace();
    }
    }
    }
    

For Copy and delete

public class MoveFileExample 
{
    public static void main(String[] args)
    {   

        InputStream inStream = null;
    OutputStream outStream = null;

        try{

            File afile =new File("C:\\folderA\\Afile.txt");
            File bfile =new File("C:\\folderB\\Afile.txt");

            inStream = new FileInputStream(afile);
            outStream = new FileOutputStream(bfile);

            byte[] buffer = new byte[1024];

            int length;
            //copy the file content in bytes 
            while ((length = inStream.read(buffer)) > 0){

                outStream.write(buffer, 0, length);

            }

            inStream.close();
            outStream.close();

            //delete the original file
            afile.delete();

            System.out.println("File is copied successful!");

        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

HOPE IT HELPS :)

ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176