java.io.File Methods

for working with files and directories

The java.io package in Java provides classes for performing input and output (I/O) operations, such as reading from and writing to files, streams, and other data sources. It's one of the core packages for handling file and stream-based I/O in Java.

Certainly! Here are some commonly used Java file handling methods along with examples:

  1. Creating a File:

    • createNewFile(): Creates a new empty file.

      File newFile = new File("example.txt");
      try {
          if (newFile.createNewFile()) {
              System.out.println("File created: " + newFile.getName());
          } else {
              System.out.println("File already exists.");
          }
      } catch (IOException e) {
          e.printStackTrace();
      }
  2. Checking File Existence and Type:

    • exists(): Checks if the file or directory exists.

      File file = new File("example.txt");
      if (file.exists()) {
          System.out.println("File exists.");
      } else {
          System.out.println("File does not exist.");
      }
    • isFile() and isDirectory(): Check if the File object represents a file or directory.

      File file = new File("example.txt");
      if (file.isFile()) {
          System.out.println("It's a file.");
      } else if (file.isDirectory()) {
          System.out.println("It's a directory.");
      }
  3. Getting File Information:

    • getName(): Returns the name of the file or directory.

      File file = new File("example.txt");
      String fileName = file.getName();
    • getAbsolutePath(): Returns the absolute path of the file or directory.

      File file = new File("example.txt");
      String absolutePath = file.getAbsolutePath();
    • length(): Returns the length of the file in bytes.

      File file = new File("example.txt");
      long fileSize = file.length();
    • lastModified(): Returns the last modified timestamp of the file.

      File file = new File("example.txt");
      long lastModified = file.lastModified();
  4. Checking Permissions:

    • canRead() and canWrite(): Check if the file or directory can be read or written.

      File file = new File("example.txt");
      if (file.canRead()) {
          System.out.println("File is readable.");
      }
      if (file.canWrite()) {
          System.out.println("File is writable.");
      }
  5. Deleting a File or Directory:

    • delete(): Deletes the file or directory.

      File file = new File("example.txt");
      if (file.delete()) {
          System.out.println("File deleted.");
      } else {
          System.out.println("Failed to delete the file.");
      }

These examples cover some of the most commonly used file handling methods in Java. You can use these methods to perform various file operations such as checking file existence, creating and deleting files, getting file information, and checking permissions.

Last updated