File handling in Java refers to working with files stored on a computer’s filesystem. It involves reading from files, writing to files, creating new files, deleting files, and manipulating file attributes. To put it simply, file handling is the process of reading and writing data into a file.
In Java, file handling is primarily achieved through classes and interfaces in the ‘java.io’ package and ‘java.nio.file, introduced in the Java 7 version. This article will cover the basics of file handling in Java, including reading, writing, creating and deleting files.
Why is File Handling Required?
File handling in Java programming is required for several reasons;
Data Persistence: File handling is the backbone of data persistence in Java. It allows data to be stored persistently on a disk and ensures that data is not lost when the program terminates, or the computer is turned off. This is a critical aspect for applications that must maintain user preferences, application state, or handle large datasets.
Data Sharing: File enables data sharing between different programs or systems. For example, documents, image configuration files, and more can be transferred between computers.
Data Backups: Files can be used to create backups of important data, ensuring that data can be restored in case of accidental deletion, hardware failure, or other disasters.
Logging and Debugging: Files are often used to log events and errors and debug information during program execution. This helps developers diagnose issues and improve software reliability.
Program
import java.io.File;
class GFG {
public static void main(String[] args) {
File obj = new File("myfile.txt");
System.out.println("File Created!");
}
}
Output
File is Created
The stream concept is used to perform I/O operations on a file. Let’s learn about it in Java.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Stream in Java
Streams in Java are an integral part of the Java I/O (Input/Output) system, providing a way to read from and write to different kinds of I/O sources. Java provides two main types of streams. Byte Stream and Character Streams.
Input Stream
The Java InputStream class is the superclass of all input streams. It reads data from numerous input devices, such as the keyboard, network, etc. InputStream is an abstract class.
The InputStream’ class in Java is a part of the ‘java.io’ package and serves as the superclass for all classes representing an input stream of bytes.
There are several subclasses of the InputStream class, which are as follows.
AudioInputStream
ByteArrayInputStream
FileInputStream
FilterInputStream
StringBufferInputStream
ObjectInpuStream
Creating an InputStream
InputStream ob = new FileInputStream() ;
In the above line, we have created inputStream using FileInputStream class.
Methods of InputStream
S No
Method
Description
1
read()
This method reads one byte of data from the input stream.
2
read(byte[] array)
This method reads the byte from the stream and stores that byte in the specified array.
3
mark()
It marks the position in the input stream until the data has been read.
4
available()
The returns the number of bytes available in the input stream
5
markSupported()
It checks if the marks() method and the reset() method is supported in the stream.
6
reset()
This method returns the control to where the mark was set inside the stream.
7
skips()
This method removes a particular number of bytes from the input stream.
8
close()
This method closes the input stream.
Output Stream
The “OutputStream” class in Java is part of the java.io package and is an abstract class representing an output stream of bytes. It is the superclass of all classes representing an output stream of bytes and is a key part of Java’s I/O system.
There are several subclasses of the OutputStream class, which are as follows.
ByteArrayOutputStream
FileOutputStream
StringBufferOutputStream
ObjectOutputStream
DataOutputStream
PrintStream
Creating an OutputStream
OutputStream ob = new FileOutputStream() ;
In the above line, An Output stream is created using FileOutputStream
Methods of OutputStream
S. No
Method
Description
1.
write()
This method write the specified byte to the output stream
2.
write(byte[] array)
This method writes the bytes which are inside a specific array to the output stream
3.
close()
This method close the output stream
4.
flush()
This method forces to write all the data present in an output stream to the destination.
There are two types of streams in the Java programming language.
Byte Stream: A byte stream reads or writes byte data. It is also divided into two types, which are as follows.
Byte Input Stream: Byte Stream reads byte data from different devices.
Byte Output Stream: It writes byte data on different output devices.
Character Stream:
This character stream is used to read or write character data. Character stream is again subdivided into two types, which are as follows.
Character Input Stream: A character stream reads character data from different devices.
Character Output Stream: A character stream outputs character data from different devices.
Java File Class Methods
The following table defines Java File Methods:
Method Name
Description
Return Type
canRead()
This method tests whether the file is readable or not
Boolean
canWrite()
This method tests whether is file is writable or not
Boolean
createNewFile()
This method creates an empty file
Boolean
delete()
It deletes a file
Boolean
exists()
It tests whether the file exists or not
Boolean
length()
This method returns the size of the file in bytes
Long
getName()
This method returns the name of the file
String
list()
This method returns array of the files in the directory
String[]
mkdir()
This method create a new directory
Boolean
getAbsolutePath()
This method returns the absolute pathname of the file.
String
File Operation in Java
The following are several operations that can be performed on a file in Java.
Create a File
Read from a file
Write to a file
Delete a file
Now, let us study each of the above operations in detail.
Create a File
We can use the createNewfile() method defined in the java io output package to create a file in Java.
If the file is successfully created, it will return a Boolean value of true, and false if it already exists.
The following program demonstrates how to create a file in Java language.
Program
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args){
try {
File Obj = new File("herovired.txt");
if (Obj.createNewFile()) {
System.out.println("File created: "+Obj.getName());
}
else {
System.out.println("File already exists.");
}
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
Output
File created: herovired.txt
Read From a File:
We can also read content from a file using the Scanner class. The program below demonstrates how to read content from a Java file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main{
public static void main(String[] args)
{
try {
File Obj = new File("herovired.txt");
Scanner Reader = new Scanner(Obj);
while (Reader.hasNextLine()) {
String data = Reader.nextLine();
System.out.println(data);
}
Reader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
Output
Neeraj Kumar
Harry Potter
Workaholic
Water Bottle
Computer System
Ninja Hattori
Write to a File:
We can also write text into a file using the FileWriter class in Java. There is a write() method to do this. The following program demonstrates the FileWriter Class example.
Program
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args)
{
try {
FileWriter Writer = new FileWriter("herovired.txt");
Writer.write("Files in Java are seriously good!!");
Writer.close();
System.out.println("Successfully written.");
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
Output
Successfully written.
Delete a File
To delete a file from the computer system, we can use the delete () method. The following demonstrates how to delete a file in Java.
Program
import java.io.File;
public class Main {
public static void main(String[] args)
{
File Obj = new File("herovired.txt");
if (Obj.delete()) {
System.out.println("The deleted file is : "
+ Obj.getName());
}
else {
System.out.println(
"Failed in deleting the file.");
}
}
}
Output
The deleted file is herovired.txt
Conclusion
In this article, we learned about File handling in Java. It is a fundamental skill for any developer, enabling the creation, manipulation, and management of files and directories by leveraging the classes and methods in the ‘java.io’ package. You can perform tasks such as reading from and writing to files, managing directories, and handling exceptions effectively. Whether dealing with simple text files or complex file structures, Understanding file handling in Java is essential for developing comprehensive and high-performing software solutions.
FAQs
What is file handling in Java?
File handling in Java refers to performing operations on files and directories, such as creating, reading, writing, and deleting files and directories. Java provides the ‘java.io’ package, which includes classes like ‘File’, ‘FileReader’, ‘FileWriter’, ‘BufferedReader’, and ‘BufferedWriter’ for handling these tasks.
What is the difference between ‘FileWriter’ and ‘BufferedWriter’?
FileWriter is a class used to write characters to a file, while ‘BufferedWriter’ efficiently writes characters to a file by buffering the characters. ‘BufferedWriter’ is generally more efficient for writing large amounts of data.
What is the ‘File’ class used for in Java?
The ‘file’ class in Java represents file and directory pathnames abstractly. It provides methods for creating, deleting, and inspecting the attributes of files and directories.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.