Сlass File in Java

Сlass File is designed to work with elements of the file system. It works directly with files and directories. This class allows you to create new elements and get information about existing ones: size, access rights, time and date of creation, path to the parent directory.

Methods of the File class

The most used methods of the File class:

  • boolean createNewFile(): attempts to create a new file;
  • boolean delete(): attempts to delete a directory or file;
  • boolean mkdir(): tries to create a new directory;
  • boolean renameTo(File dest): attempts to rename a file or directory;
  • boolean exists(): checks if a file or directory exists;
  • String getAbsolutePath(): returns the absolute path for the path passed to the object's constructor;
  • String getName(): returns the short name of a file or directory;
  • String getParent(): returns the name of the parent directory;
  • boolean isDirectory(): returns true if a directory is located in the specified path;
  • boolean isFile(): returns true if a file is located at the specified path;
  • boolean isHidden(): returns true if the directory or file is hidden;
  • long length(): returns the size of the file in bytes;
  • long lastModified(): returns the time the file or directory was last modified;
  • String[] list(): returns an array of files and subdirectories that are in a specific directory;
  • File[] listFiles(): returns an array of files and subdirectories that are in a specific directory.

FileFilter interface

The FileFilter interface is used to check if a File object meets a certain condition. This interface contains a single boolean accept (File pathName) method. This method must be overridden and implemented. For example:

public boolean accept(final File file) {
    return file.isExists() && file.isDirectory();
}

Select all the items of a specific catalog by criterion (for example, with a specific extension)

The File.listFiles() method returns an array of File objects contained in the directory. The method can take as a parameter an object of a class that implements FileFilter. This allows to include in the list only those elements for which the accept method returns true (the criterion can be the length of the file name or its extension).


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed