Sep 15, 2013

How to Create, Rename, Delete a file in Java - createNewFile(), renameTo() and delete()

Create operation:- In Java file is created using createNewFile(fileName) method associated with File class.It creates a new, empty file named by abstract pathname, if and only if file with this name does not exist and returns boolean value true. If file exists it returns false and file is not created.
Rename operation:- For renaming a file we have renameTo(dest). It renames file name associted with File object on which this method is called to "dest"(abstract path name specified.).Rename operation might not be able to move a file from one filesystem to another, that's why some times it is called platform dependent operation.On success it also returns boolean true otherwise false.
Delete operation:- For deleting a file from file system we have delete()/deleteOnExit() method.
  1. delete() method will delete specified abstract file/directory specified in File object and on success returns true otherwise false.
  2. deleteOnExit() method will request VM to delete specified file or directory when Virtual machine is shutting down gracefully. Files (or directories) are deleted in the reverse order that they are registered.Once a file registered for deletion cannot be reversed back. 
import java.io.File;
import java.io.IOException;

/**
 * @author devinline
 *
 */
public class FileOperations {

 public static void createFile(File file) {
  if (!file.exists()) {
   try {
    Boolean status = file.createNewFile();
    if (status) {
     System.out.println(file.getAbsolutePath()
       + " created successfully ");
    }
   } catch (SecurityException | IOException e) {
    // throws SecurityException, if write access not allowed
    e.printStackTrace();
   }
  }
 }

 public static void renameFile(File file) {
  File dest = new File(System.getenv("user.dir"), "modifiedInput.xml");
  if (file.exists()) {
   try {
    Boolean status = file.renameTo(dest);
    if (status) {
     System.out.println(file.getName() + " renamed to "
       + dest.getName());
    }
   } catch (NullPointerException ex) {
    // throws NPE, if dest is null;
    ex.printStackTrace();
   }

  }
 }

 public static void deleteFile(File file) {
  if (file.exists()) {
   Boolean status = file.delete();
   if (status) {
    System.out.println(file.getName() + " deleted successfully!! ");
   }
  } else {
   System.out.println("input.xml does not exist," +
     "It means reNameTo executed succesfully!!");
   // file object with modified file name.
   File fileModified = new File("modifiedInput.xml");
   Boolean newStatus = fileModified.delete();
   if (newStatus)
    System.out.println("Modified file deleted successfully!!");
  }
 }

 public static void main(String[] args) throws IOException {
  /* Absolute path = VM fills this space + input.xml */
  File fileObj1 = new File("input.xml");

  /* Absolute path = parent directory + input.xml */
  File fileObj2 = new File("E:\\dev\\java\\javaIO", "input.xml");
  // Create input.xml
  createFile(fileObj1);
  // create renameFile input.xml
  renameFile(fileObj1);
  // delete file
  deleteFile(fileObj1);
 }

}
========Sample output===============
C:\zytham\EclipseJunoWorkSpace\DevShine\input.xml created successfully
input.xml renamed to modifiedInput.xml
input.xml does not exist.It means reNameTo executed succesfully!!
Modified file deleted successfully!!
 =================================
Refer above sample code lines and walk through code lines, in main method , File object fileObj1 is created by passing an abstract file name -"input.xml". Similarly, fileObj2 is created passing parent directory("E:\\dev\\java") and file name. So, VM creates absolute path with these two parameters.
Now, we have file object, where file will be created in our file system?- current working directory,   by default Virtual machine(VM) uses the directory in which the Java program/application is executed as the current working directory(or current path). However, we can override this by specifying the user.dir system property.VM makes absolute path by combining System.getProperty("user.dir") + abstract file name.
In createFile(fileObj1) method, first existence of file is checked with exist() method and if it returns false then file is created using createFile() method.Possible exception thrown by createFile() method is SecurityException and IOException.(Exception concatenation with | (pipe operator) works in java 7 and later.)
In renameFile(fileObj1) method, nwe file object is created and passed to renameTo() method and input.xml is renamed to modifiedInput.xml. Method renameTo() does not throw IOException instead it throws NPE when dst file object is null.
In deleteFile(fileObj1) method, input.xml not deleted since it does not exist. It has been renamed to modifiedInput.xml.In else block we again prepare new file object and then file modifiedInput.xml deleted.

Location: Coimbatore, Tamil Nadu, India