In Java, file handling means working with files like creating them, reading data, writing data or deleting them. It helps a program save and use information permanently on the computer.
With the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used to create an object of the class and then specifying the name of the file.
Why File Handling is Required?
- To store data permanently instead of keeping it only in memory.
- To read and write data from/to files for later use.
- To share data between different programs or systems.
- To organize and manage large data efficiently.
Example:
Java
// Importing File Class
import java.io.File;
class Geeks
{
public static void main(String[] args)
{
// File name specified
File obj = new File("myfile.txt");
System.out.println("File Created!");
}
}
Output:
File Created!
In Java, streams are used to perform input and output operations on files. So, let’s first understand what a stream is.
Streams in Java
In Java, a sequence of data is known as a stream. This concept is used to perform I/O operations on a file. Below are the types of Streams:
An Input Stream in Java is used to read data from a source, such as a file, keyboard or network. It reads the data as a sequence of bytes and is represented by classes that end with InputStream (e.g., FileInputStream).
There are several subclasses of the InputStream class, which are as follows:
- AudioInputStream
- ByteArrayInputStream
- FileInputStream
- FilterInputStream
- StringBufferInputStream
- ObjectInputStream
Creating an InputStream:
InputStream is an abstract class, so it cannot be used directly. Instead, its subclasses are used to read data.
// Creating an InputStream
InputStream obj = new FileInputStream();
Note: We can create an input stream from other subclasses as well as InputStream.
Common Methods of InputStream:
Method | Description |
---|
read() | Reads one byte of data from the input stream. |
read(byte[] array)() | Reads byte from the stream and stores that byte in the specified array. |
mark() | It marks the position in the input stream until the data has been read. |
available() | Returns the number of bytes available in the input stream. |
markSupported() | It checks if the mark() method and the reset() method is supported in the stream. |
reset() | Returns the control to the point where the mark was set inside the stream. |
skip() | Skips and removes a particular number of bytes from the input stream. |
close() | Closes the input stream. |
2. Output Stream
An Output Stream in Java is used to write data to a destination, such as a file, console or network. It writes the data as a sequence of bytes and is represented by classes that end with OutputStream (e.g., FileOutputStream).
There are several subclasses of the OutputStream class which are as follows:
- ByteArrayOutputStream
- FileOutputStream
- StringBufferOutputStream
- ObjectOutputStream
- DataOutputStream
- PrintStream
Creating an OutputStream:
OutputStream is also an abstract class, so it cannot be used directly. Instead, its subclasses are used to read data.
// Creating an OutputStream
OutputStream obj = new FileOutputStream();
Note: We can create an output stream from other subclasses as well as OutputStream.
Common Methods of OutputStream:
Method | Description |
---|
write() | Writes the specified byte to the output stream. |
write(byte[] array) | Writes the bytes which are inside a specific array to the output stream. |
close() | Closes the output stream. |
flush() | Forces to write all the data present in an output stream to the destination. |
Type of Streams based on Data-types
1. Byte Stream
This stream is used to read or write byte data. The byte stream is again subdivided into two types which are as follows:
- Byte Input Stream: Used to read byte data from different devices.
- Byte Output Stream: Used to write byte data to different devices.
2. Character Stream
This stream is used to read or write character data. Character stream is again subdivided into 2 types which are as follows:
- Character Input Stream: Used to read character data from different devices.
- Character Output Stream: Used to write character data to different devices.
File Operations
The following are the 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
1. Create a File
- In order to create a file in Java, you can use the createNewFile() method.
- If the file is successfully created, it will return a Boolean value true and false if the file already exists.
Example:
Java
import java.io.File;
import java.io.IOException;
public class CreateFile
{
public static void main(String[] args)
{
try {
File Obj = new File("myfile.txt");
// Creating File
if (Obj.createNewFile()) {
System.out.println("File created: " + Obj.getName());
}
else {
System.out.println("File already exists.");
}
}
// Exception Thrown
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
Output:
Output2. Write to a File
We use the FileWriter class along with its write() method in order to write some text to the file.
Example:
Java
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile
{
public static void main(String[] args)
{
// Writing Text File
try {
FileWriter Writer = new FileWriter("myfile.txt");
// Writing File
Writer.write("Files in Java are seriously good!!");
Writer.close();
System.out.println("Successfully written.");
}
// Exception Thrown
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
Output:
Output3. Read from a File
We will use the Scanner class in order to read contents from a file.
Example:
Java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile
{
public static void main(String[] args)
{
// Reading File
try {
File Obj = new File("myfile.txt");
Scanner Reader = new Scanner(Obj);
// Traversing File Data
while (Reader.hasNextLine()) {
String data = Reader.nextLine();
System.out.println(data);
}
Reader.close();
}
// Exception Cases
catch (FileNotFoundException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
Output:
Output4. Delete a File
We use the delete() method in order to delete a file.
Example:
Java
import java.io.File;
public class DeleteFile
{
public static void main(String[] args)
{
File Obj = new File("myfile.txt");
// Deleting File
if (Obj.delete()) {
System.out.println("The deleted file is : " + Obj.getName());
}
else {
System.out.println(
"Failed in deleting the file.");
}
}
}
Output:
OutputRelated Article
Explore
Basics
OOPs & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java