Java – File Class3 min read

Java file Class deals directly with the file and file system. That is, it is the abstract representation of file or directory pathname. It defines the properties of the file itself rather than describing how information is stored in or retrieved from files.

File class contains various methods for working with the pathname, deleting and renaming files, creation of new directories, and many more. A file object is created to manipulate with disk’s permissions, time, date, and directory path, etc.

Create File Object:

A File object is created as shown below,

To create a file object, following constructor can be used:

  • File(File parent, String child):
    Creates a new File instance from a parent abstract pathname and a child pathname string.
  • File(String pathname):
    Creates a new File instance by converting the given pathname string into an abstract pathname.
  • File(String parent, String child):
    Creates a new File instance from a parent pathname string and a child pathname string.
  • File(URI uri):
    Creates a new File instance, URI into an abstract pathname.

Some Useful Methods:

  • static File createTempFile(String prefix, String suffix): This method is used to create an empty file in the default temporary-file directory.
  • boolean canRead(): This method is used to test whether the application can read the file denoted by this abstract pathname.
  • boolean canWrite(): This method is used to test whether the application can modify the file denoted by this abstract pathname.
  • boolean delete(): This method is used to delete the file or directory denoted by this abstract pathname.
  • boolean createNewFile(): This method is used for atomically creating a new, empty file named by this abstract pathname.
  • boolean canExecute(): Method is used to test whether the application can execute the file denoted by this abstract pathname.
  • boolean isDirectory(): Method is used to test whether the file denoted by this pathname is a directory.
  • boolean isFile(): Method is used to test whether the file denoted by this abstract pathname is a normal file.
  • String getName(): Method is used to return the name of the file or directory denoted by this abstract pathname.
  • String getParent(): Method is used to return the pathname string of this abstract pathname’s parent.
  • boolean mkdir(): Method is used to create the directory named by this abstract pathname.
  • URI toURI(): Method is used to construct a file URI that represents this abstract pathname.
  • File[] listFiles(): Method is used to return an array of abstract pathnames denoting the files in the directory.

Java Program example to demonstrate Files Class

1. To check whether the new file is created or it already exists:

Output:

A new text file named ‘javaCode.txt‘ will be created at the same directory where you saved the java file.


FIles I/O