File class Changing File Properties


File class Changing File Properties

Summary: By the end of this tutorial "File class Changing File Properties", you will come to know how to create and delete a file or create a new directory etc using Java code.

After retrieving the properties of a file with File class, let us attempt to change the properties of a file programmatically like creating, renaming and deleting a file, creating a new directory or deleting a existing directory etc.

Following are the supporting methods.

1. createNewFile() : Creates a new file. If the file is successfully created returns a boolean value of true.
2. delete() : Deletes a file or directory. If successfully deleted, the method returns true.
3. deleteOnExit() : : Deletes the file by the time the running program execution is over.
4. mkDir() : Creates a new directory. If the new directory is created successfully, it returns true.

Program using above methods
import java.io.*;
public class FODemo
{
  public static void main(String args[]) throws IOException
  {                              	                      // link a file to File class
    File file1 = new File("Resume.txt");
    boolean yes = false;
    if( ! file1.exists() )
    {
      yes = file1.createNewFile(); 
    }
    if(yes)         
    {
      System.out.println("New file is created");
    }
    File file2 = new File("Tax.txt");
    File file3 = new File("Acccounts.txt");
    boolean b = false;
          
    if( file2.exists() )
    {
      b = file2.renameTo(file3);
    }
    if(b)
    {
      System.out.println("Tax.txt is renamed to " + file2.getName());
    }
    File file4= new File("expenses");
    boolean b1 = file4.mkdir();
    if(b1)
    {
      System.out.println("New directory is created");
    }
     File file5= new File("Income.txt");
     boolean b2 = file5.delete();
     if(b2)
     {
       System.out.println("Directory is deleted");
     }
     File file6 = new File("Raju.txt");
     file6.deleteOnExit();
   }   
}   

File file1 = new File("Resume.txt");
yes = file1.createNewFile();

A new file Resume.txt is created. It is the correct style programming to check whether the file is already existing or not.

file2.renameTo(file3);

The existing file Tax.txt is renamed to Accounts.txt.

File file4= new File(“expenses”);
boolean b1 = file4.mkdir();

A new directory expenses is created in the current directory.

File file5= new File(“Income.txt”);
boolean b2 = file5.delete();

The file Income.txt is deleted while the program is being executed.

File file6 = new File(“Raju.txt”);
file6.deleteOnExit();

The file Raju.txt is deleted at the end of the current Java program execution. That is, the Raju.txt file can be used by the running program as long as the program does not exit.

Pass your comments and suggestions to improve this posting, "File class Changing File Properties".

Leave a Comment

Your email address will not be published.