81. File Handling
81. File Handling
File handling in Java implies reading from and writing data to a file. The
File class from the java.io package, allows us to work with different
formats of files. In order to use the File class, you need to create an
object of the class and specify the filename or directory name.
- Create an object of file and check whether the file exists or not
import java.io.File;
1
Now let’s see different methods available in File class
import java.io.File;
2
- getName():
This method returns the Name of the given file object. The function
returns a string object which contains the Name of the given file
object.
import java.io.File;
- getParent():
This method returns a String which denotes the pathname string of
the parent directory named by this abstract pathname, or null if this
pathname does not name a parent.
import java.io.File;
3
public class Alpha {
Output:
- getAbsolutePath():
The getAbsolutePath() method is a part of the file class. This
function returns the absolute pathname of the given file object.If
the pathname of the file object is absolute then it simply returns the
path of the current file object.
import java.io.File;
4
String path =
"C:\\Users\\Megha\\Desktop\\MyFiles\\data.txt";
System.out.println(file.getAbsolutePath());
}
Output:
- isFile()
The isFile() function is a part of the File class in Java. This
function determines whether the is a file or Directory denoted by
the abstract filename is File or not. The function returns true if the
abstract file path is File else returns false.
import java.io.File;
System.out.println(file.isFile());
5
}
Output:
- isDirectory()
This function determines whether the is a file or directory denoted
by the abstract filename is Directory or not.The function returns
true if the abstract file path is Directory else returns false.
import java.io.File;
System.out.println(file.isDirectory());
}
6
Output:
- createNewFile():
The createNewFile() method creates a new and empty file with a
specified name. This operation succeeded when the name did not
yet exist. Checking for the existence of the file and creation of the
file are atomic operations.
import java.io.File;
public class Alpha {
public static void main(String[] args) {
file.createNewFile();
}
}
Output:
Here you are getting IOException because the createNewFile() will throw
IOException so you need to handle this exception using throw or try-
catch
7
import java.io.File;
import java.io.IOException;
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- mkdir():
The mkdir() function is used to create a new directory denoted by
the abstract pathname. The function returns true if the directory is
created else returns false.
import java.io.File;
public class Alpha {
8
File file = new File(path);
System.out.println(file.mkdir());
}
- list()
Returns an array of strings naming the files and directories in the
directory denoted by this abstract pathname.
import java.io.File;
Output:
9
- delete()
Deletes the file or directory denoted by this abstract pathname. If
this pathname denotes a directory, then the directory must be
empty in order to be deleted.
import java.io.File;
Output:
10
File Writer:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
FileWriter writer;
11
Now Hello World String is written inside the data.txt file
- Write a program to take three words from the user and write that
inside the file
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
12
}
Output:
Alpha.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
13
// Create an object of file writer
try {
String s1 = scan.next();
String s2 = scan.next();
String s3 = scan.next();
writer = new FileWriter(file, true);
writer.write(s1);
writer.write(s2);
writer.write(s3);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
finally{
scan.close();
writer.close();
}
}
Output:
Now if you observe from the output, the new input is appended to the
existing data.
14
File Reader:
Java FileReader class is used to read data from the file. It returns data in
byte format like FileInputStream class.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Alpha {
public static void main(String[] args) {
// Specify the directory in which file exists
String path =
"C:\\Users\\Megha\\Desktop\\MyFiles\\data.txt";
15
Output:
16
Here if you observe from the above output, it is giving the ascii value of
the first character present inside the file because it reads the character
and converts it to integer value. If you want the character instead of integer
then you need to do explicit type cast as shown below.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Alpha {
public static void main(String[] args) {
// Specify the directory in which file exists
String path =
"C:\\Users\\Megha\\Desktop\\MyFiles\\data.txt";
Output:
17
To read all the string present inside the file you need to create an array
using which you can read
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Alpha {
public static void main(String[] args) {
// Specify the directory in which file exists
String path =
"C:\\Users\\Megha\\Desktop\\MyFiles\\data.txt";
FileReader reader = null;
char[] ar = new char[15];
Output:
18
Now as you can see from the above example here you need to define the
size of the array in which the data present in the file is stored but if you
don't know the number of characters present in the file then you cannot
read the complete data present inside the file.
Now to read complete data present in the file make use of read() and do
this operation repeatedly unless you encounter last character
Alpha.java
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Alpha {
public static void main(String[] args) {
// Specify the directory in which file exists
String path =
"C:\\Users\\Megha\\Desktop\\MyFiles\\data.txt";
FileReader reader = null;
19
try {
reader = new FileReader(path);
int c = reader.read();
while(c!=-1) {
System.out.print((char)c);
c = reader.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
Output:
20
- Now let’s create one more file and copy all the data from one file to
another file
● Create an object of filewriter and filereader
● Read the character present inside one file using read() and
write to one more file using write()
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Alpha {
public static void main(String[] args) {
// Specify the directory in which file exists
String path =
"C:\\Users\\Megha\\Desktop\\MyFiles\\data.txt";
String path1 =
"C:\\Users\\Megha\\Desktop\\MyFiles\\exmp.txt";
FileReader reader = null;
FileWriter writer = null;
// Read the character from data file and write to exmp file
int c = reader.read();
while(c!=-1) {
writer.write(c);
c = reader.read();
}
writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e1) {
e1.printStackTrace();
21
}
}
}
The data is present in the data file to the exmp file, but here if you observe
here we are reading each character one by one which is not efficient when
there are billions of characters present in the file.
- Now let’s see how to read the data from the file using BufferedReader.
BufferedReader will read line by line.
● Create an object of file reader
● Convert file reader to bufferedreader by creating an object of
buffered reader
● Call readLine() to read the each line present inside the file
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
22
System.out.println(reader2.readLine());
System.out.println(reader2.readLine());
System.out.println(reader2.readLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
}
Output:
Here we have called readLine() multiple times to read all the lines present
inside the file. Instead of that we can make use of a loop and read all lines
until the end of the file.
import java.io.BufferedReader;
23
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Alpha {
public static void main(String[] args) {
// Specify the directory in which file exists
String path =
"C:\\Users\\Megha\\Desktop\\MyFiles\\data.txt";
FileReader reader = null;
BufferedReader reader2 = null;
try {
reader = new FileReader(path);
reader2 = new BufferedReader(reader);
String line = reader2.readLine();
while(line != null) {
System.out.println(line);
line = reader2.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
}
Output:
24
- Write a program to count number of lines in the file
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
try {
reader = new FileReader(path);
reader2 = new BufferedReader(reader);
String line = reader2.readLine();
int count = 0;
while(line != null) {
System.out.println(line);
count++;
line = reader2.readLine();
}
System.out.println(count);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
25
Output:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
try {
reader = new FileReader(path);
reader2 = new BufferedReader(reader);
String line = reader2.readLine();
int count = 0;
int sum = 0;
while(line != null) {
count++;
int l = line.length();
26
sum +=l;
line = reader2.readLine();
}
System.out.println(count);
System.out.println(sum);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
27
Scenario 1: Write a program to read the name from the file and phone
number from another file, now merge two data and write into file in a
format shown below
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
28
FileWriter writer = null;
try {
reader = new FileReader(path);
reader1 = new BufferedReader(reader);
reader2 = new FileReader(path1);
reader3 = new BufferedReader(reader2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
29
Now let’s see how you can write into the file using buffered writer
String path =
"C:\\Users\\Megha\\Desktop\\MyFiles\\data.txt";
- Using bufferedWriter call write() to write the data into the text
bf.write("India");
Alpha.java
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
30
try {
writer = new FileWriter(path);
bf = new BufferedWriter(writer);
bf.write("India");
bf.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
}
- Now let’s see to take integer value from the user and write into the
file
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
31
writer
FileWriter writer = null;
BufferedWriter bf = null;
try {
writer = new FileWriter(path);
bf = new BufferedWriter(writer);
bf.write(n);
bf.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
Output:
As you can see from the above output, the user has given 65 but in the
file ascii character of the number is stored, it is because write() inside the
buffered writer will write the character into the file.
32
If you try to read float value from the user and try to write into the file using
buffered writer and file writer you will get an error. It is because it can read
int, String and character array.
- Create an object of PrintWriter and call print() to write the value into
the file
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
try {
writer = new PrintWriter(path);
writer.print(f);
writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e1) {
e1.printStackTrace();
}
33
}
Output:
As you can see from the above output, successfully float value is written
inside the file.
Using PrintWriter you can write all different types of values inside the file
by calling print().
- Now let’s read integer, float, boolean value from the user and write
into the file
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
34
"C:\\Users\\Megha\\Desktop\\MyFiles\\data.txt";
Output:
35
36