File Handling Basics

In Java, managing files and directories is an essential skill, especially when building applications that interact with the file system. The Java NIO (New I/O) API provides a more efficient and flexible way to handle file and directory operations compared to the older File API.

Creating, Deleting, and Renaming Files

Java provides various ways to create, delete, and rename files using the Files class from the java.nio.file package.

  • Creating Files: To create a new file, we can use the Files.createFile() method. If the file already exists, an exception will be thrown.

  • Deleting Files: To delete a file, we can use the Files.delete() method. It throws an exception if the file doesn’t exist.

  • Renaming Files: To rename a file, we can use the Files.move() method. This method can also be used to move files to different locations.

Checking if a File Exists

To check if a file exists, you can use the Files.exists() method. It returns true if the file exists, and false otherwise.

Getting File Properties

Java allows you to retrieve file properties such as size, last modified date, and file permissions using the Files class.

  • File Size: To get the size of a file, use the Files.size() method, which returns the size in bytes.

  • Last Modified Date: To get the last modified date of a file, use the Files.getLastModifiedTime() method.

  • File Permissions: To check the file permissions, you can use Files.isReadable(), Files.isWritable(), and Files.isExecutable() methods.

Creating Directories and Subdirectories

To create directories and subdirectories, use the Files.createDirectory() and Files.createDirectories() methods. The createDirectories() method is particularly useful as it creates any nonexistent parent directories as well.

Relative and Absolute File Paths

A file path can be absolute or relative. Absolute paths provide the full path from the root directory, while relative paths are based on the current working directory.

  • Absolute Path: To get the absolute path of a file, use the toAbsolutePath() method.

  • Relative Path: Relative paths are useful when you want to specify a file location relative to the current working directory.