Program to Move a file - in java file IO




java.io.File does not provide any direct method to move a file.

We must follow these steps to move a file >
1- Copy file from sourcePath to destinationPath
2- delete file from sourcePath



Program to Move a file in java - file IO >


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/** JavaMadeSoEasy.com */
public class MoveFile {
   public static void main(String... args) {
          String sourcePath ="c:/myFile.txt";
          String destinationPath= "c:/newFolder/myFile.txt";
         
          FileInputStream fis= null;
          FileOutputStream fos = null;
          try {
                 //1- Copy file from sourcePath to destinationPath
                 fis = new FileInputStream(sourcePath);
                 fos = new FileOutputStream(destinationPath);
                 byte[] b = new byte[1024];
                 int ch;
                 while ((ch = fis.read(b)) != -1) { //read bytes from myFile.txt
                       fos.write(b, 0, ch); //write bytes in myFileCopy.txt
                 }
                 fos.flush(); // bytes in buffer are written in file
                
                 System.out.println(sourcePath+" has been successfully moved to " + destinationPath);
          } catch (IOException e) {
                 e.printStackTrace();
          } finally {
                 try {
                       if (fis != null){
                              fis.close(); //close FileInputStream
                       }
                       if (fos != null){
                              fos.close(); //close FileOutputStream
                       }
                 } catch (IOException e) {
                       e.printStackTrace();
                 }
          }
         
          //2- delete file from sourcePath
          new File(sourcePath).delete();
         
   }
}
/* OUTPUT
c:/myFile.txt has been successfully moved to c:/newFolder/myFile.txt
*/


RELATED LINKS>

Create File using createNewFile() method in java file IO


Copy a file in java 2 in ways - use org.apache.commons.io.FileUtils's copyDirectory(sourceDirectory, destDirectory)


Program to Delete a file - in java file IO


Program to Find file exists or not - in java file IO



Program on How to hide and unHide file or Directory in java 7 using java.nio.file



Program to Make a file READ ONLY in java

Program to Find file is Read only or not in java 7



Program to Create Directory - Single and multiple (i.e. parent and child directories) in java file IO

2 Program to Delete a Directory

Traverse a Directory (all sub-directories and files) in 2 ways




eEdit
Must read for you :