File Handling In Java
Java provides a file handling concept to work with files. We can read/write data in file with the help of Java File class.
Importance of File Handling
- When the first version of Java was released in 1995,there was no database concept to store data. Then, by default,the data storage platform was files only.
- File handling is an important aspect of any programming language. It allows users to read and write data to files. Java has several predefined methods that make it easy to work with files.
- In other words file handling is simple mechanism of reading and writing data to a file.
Java File Class Methods
Java provides several predefined methods that make file handling easy.
Methods | Return Type | Applications |
exists() | boolean | It is used to check whether specified file exist or not. |
getName() | String | It returns the name of specified file. |
length() | Long | length() is used to find the size of file in bytes. |
list() | String[] | It returns an array of files available in present directory. |
getAbsolutePath() | String | It returns complete path of the specified file. |
delete() | boolean | This method is used to delete file from the directory. |
canRead() | boolean | It checks whether the file is readable or not. |
canWrite() | boolean | It checks whether the file is writable or not. |
mkdir() | boolean | First, it checks whether the specified directory exists or not; if not, It creates a new directory. |
File Operations
Following are four major operations performed in file handling .
- Creating File
- Reading File
- Writing File
- Deleting File
File i/o Package
Before perfoming any file handling operations we need to import a package.
import java.io.File;
All the required File’s classes and methods are defined in side java.io.File package.