Java File Class in Detail
The java.io.File
class is used to represent file and directory pathnames in an abstract manner. It doesn't represent the contents of a file but allows you to create, delete, check properties (like size, existence), and manipulate files or directories.
1. Constructors of File Class#
Example:#
Output:#
2. Commonly Used Methods with Examples#
● boolean createNewFile()
#
Creates a new file if it doesn't exist.
Output:#
● boolean exists()
#
Checks whether the file exists.
Output:#
● boolean delete()
#
Deletes the file or directory.
Output:#
● String getName()
, String getPath()
, String getAbsolutePath()
#
These methods provide various representations of the file path.
Output:#
● boolean isDirectory()
, boolean isFile()
#
Checks whether it is a directory or file.
Output:#
● String[] list()
#
Returns the list of files and directories in a directory.
Output:#
● long length()
#
Returns the file size in bytes.
Output:#
● boolean mkdir()
and boolean mkdirs()
#
Creates a single directory or multiple directories.
Output:#
3. When to Use the File Class?#
- Use it when you need to interact with the file system—checking if files/directories exist, creating or deleting files, listing directory contents, etc.
- It acts as a foundation for many file handling operations and is frequently used with other I/O classes for reading or writing content.
Conclusion#
In this blog, we explored the File
class in Java, its constructors, and commonly used methods with practical examples and outputs. We saw how it helps us interact with the file system for operations like creation, deletion, and fetching metadata of files or directories.
In the next blog, we will dive into Reader
and Writer
classes, which are used for character-based input and output operations.