Java | File class

05 min read

File class:

A class which describes the properties of a file instead of creating streams for those files.

Constructors:

  • File (String directorypathname) will create the obj within the current directory
  • File(String directory, String filename) will create the obj within the directory specified by 1st argument and 2nd argument is the child of that directory which can be a file or directory.

Important file methods:

  • getName() — returns the name of the file
  • getParent() — returns the name of the parent directory
  • getPath()
  • getAbsolutePath()
  • can Write() — returns a Boolean value denoting whether the file can be written canRead()
  • isFile() —returns true if the object is a file
  • isDirectory()- returns true if the object is a directory
  • length() — gives the size of the file
  • lastModified() - gives the date when the file was last modified

 

A directory in java is also treated as a file with one additional property — using the list() method, a list of filenames within that directory can be examined. list() method can be called on the directory object to extract the list of other files and directories inside it.

Two forms:

1) String[]  list() — the list of files is returned in an array of String objects

The second form of list is used to list only the name of the specific types of files eg., only .txt files or only .c files and so on

2) String[] list(FileNameFilter obj)

FileNameFilter:

It is an interface which defines only a single method accept(). It is used to list only the files that match a certain file name pattern or filter. As per the syntax of list() method, an obj of FileNameFilter is required. But FileNameFilter is an interface for which objects cannot be created. So, first define a class by implementing the FileNameFilter interface. Define the method accept() for this class and create an obj for this class Use this object as an argument for the list() method. boolean accept(File directory, String Filename) — returns true for those files in the directory object( given as 1st argument) which matches with the filename (specified as 2nd argument) else returns false.

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error