Construction. The File Class

[comp1110-95]

Java's File class specifies objects that represent abstract file paths, and through them, the directories and files in your file system. To create an instance, you need to use the new operator, and give a path as an argument.

File f = new File(pathToFile);

With the above f, you can now call a number of methods:

  • f.exists()

    Returns a boolean that is true if the file or directory exists, false if it does not

  • f.delete()

    Deletes the file or directory. A directory has to be empty for this to work.

  • f.getName()

    Returns the name of the file or directory - useful if you are just given a File object without having created it.

  • f.getParent()

    Returns a different File object representing the parent directory of the file or directory, if that exists (the root directort "/" has no parent, so this would return null)

  • f.isDirectory()

    Returns true if the path represents a directory

  • f.isFile()

    Returns true if the path represents a file

  • f.listfiles()

    If f represents a directory, returns an array containing File objects representing all the files contained in the directory

  • f.mkdir()

    Creates a directory at the path represented by f

You can further use it as an argument to create FileReaders and FileWriters.

bars magnifying-glass caret-down plus minus arrow-right xmark