File class Changing File Properties

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

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 Reply

Your email address will not be published. Required fields are marked *