Master java skills

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

  1. 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.
  2. 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.
  3. 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.

MethodsReturn TypeApplications
exists()booleanIt is used to check whether specified file exist or not.
getName()StringIt returns the name of specified file.
length()Longlength() is used to find the size of file in bytes.
list()String[]It returns an array of files available in present directory.
getAbsolutePath()StringIt returns complete path of the specified file.
delete()booleanThis method is used to delete file from the directory.
canRead()booleanIt checks whether the file is readable or not.
canWrite()booleanIt checks whether the file is writable or not.
mkdir()booleanFirst, 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.