File handling in Java allows you to read from and write to files, which is a fundamental part of working with data. Java provides various classes and methods in the java.io and java.nio packages to work with files. Here’s an overview of file handling in Java.
Why File Handling is Required :-
Streams in Java :-
Input Stream:-
In Java, an input stream is a fundamental concept for reading data from various input sources, such as files, network connections, or other input streams. Input streams are part of the Java I/O (Input/Output) library, and they provide a way to read data sequentially from the source. The java.io package, which has been around since the early days of Java, offers several classes for working with input streams.
There are several subclasses of the InputStream class, which are as follows:
Creating an InputStream
// Creating an InputStream
InputStream obj = new FileInputStream();
Here, an input stream is created using FileInputStream.
Methods of InputStream :-
S/No. | Method | Description |
---|---|---|
1 | read() | Reads one byte of data from the input stream. |
2 | read(byte[] array)() | Reads 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() | Returns the number of bytes available in the input stream. |
5 | markSupported() | It checks if the mark() method and the reset() method is supported in the stream. |
6 | reset() | Returns the control to the point where the mark was set inside the stream. |
7 | skips() | Skips and removes a particular number of bytes from the input stream. |
8 | close() | Closes the input stream. |
Output Stream:
In Java, an output stream is a fundamental concept for writing data to various output destinations, such as files, network connections, or other output streams. Output streams are part of the Java I/O (Input/Output) library and provide a way to write data sequentially to the target destination. The java.io package offers several classes for working with output streams.
The OutputStream class is an abstract superclass for all output streams in Java. It defines the basic methods for writing data. Here are some of the key methods available in the OutputStream class:
There are several subclasses of the OutputStream class which are as follows:
Creating an OutputStream
// Creating an OutputStream
OutputStream obj = new FileOutputStream();
Here, an output stream is created using FileOutputStream.
Methods of OutputStream
S/No. | Method | Description |
---|---|---|
1 | write() | Writes the specified byte to the output stream. |
2 | write(byte[] array) | Writes the bytes which are inside a specific array to the output stream. |
3 | close() | Closes the output stream. |
4 | flush() | Forces to write all the data present in an output stream to the destination. |
File Class Methods :-
The java.io.File class provides methods for working with files and directories in Java. This class allows you to create, manipulate, and obtain information about files and directories. Here are some commonly used methods of the File class:
S/No. | Method | Description | Return Type |
---|---|---|---|
1 | canRead() | It tests whether the file is readable or not. | Boolean |
2 | canWrite() | It tests whether the file is writable or not. | Boolean |
3 | createNewFile() | It creates an empty file. | Boolean |
4 | delete() | It deletes a file. | Boolean |
5 | exists() | It tests whether the file exists or not. | Boolean |
6 | length() | Returns the size of the file in bytes. | Long |
7 | getName() | Returns the name of the file. | String |
8 | list() | Returns an array of the files in the directory. | String |
9 | mkdir() | Creates a new directory. | Boolean |
10 | getAbsolutePath() | Returns the absolute pathname of the file. | String |
Let us now get acquainted with the various file operations in Java.
File operations in Java :-
Example :-
public void CreateFile()
{
// Specify a file name and path
String fileName = “example.txt”;
// Create a new file
try {
File file = new File(fileName);
if (file.createNewFile())
{
System.out.println(“File created: ” + file.getName());
}
else {
System.out.println(“File already exists.”);
}
}
catch (IOException e)
{
System.err.println(“An error occurred while creating the file.”);
e.printStackTrace();
}
}
In this example :-
Note :- Make sure you specify the correct file name and path based on your requirements.
Here are the basic steps to read from a file in Java:
Example :-
public void ReadFile()
{
// Read data from the file
try {
FileReader reader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
System.out.println(“Reading data from the file:”);
while ((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
}
catch (IOException e)
{
System.err.println(“An error occurred while reading from the file.”);
e.printStackTrace();
}
}
In this example :-
In this example, we open a file called “FileName.txt,” read its contents line by line, and print them to the console. The try-with-resources block is used to ensure that the file is properly closed after reading, even if an exception occurs.
For binary data or more advanced file manipulation, consider using classes like FileInputStream, BufferedInputStream, or java.nio.file utilities.
Using io package (Stream-based approach) :- In this approach, you typically use FileOutputStream or FileWriter to write data to a file.
Example :–
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample
{
public static void main(String[] args)
{
String content = “Hello, world!”;
String fileName = “example.txt”;
try {
FileWriter writer = new FileWriter(fileName);
writer.write(content);
writer.close();
System.out.println(“Data written to ” + fileName);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Using the delete() method :- You can use the delete() method of the File class to delete a file. This method returns true if the file was successfully deleted and false if the file could not be deleted for some reason (e.g., the file does not exist).
Example :–
import java.io.File;
public class FileDeletionExample
{
public static void main(String[] args)
{
String filePath = “path/to/your/file.txt”; // Replace with the path to the file you want to delete
File file = new File(filePath);
if (file.delete())
{
System.out.println(“File deleted successfully.”);
}
else
{
System.out.println(“Failed to delete the file.”);
}
}
}
1. WriteToFile :-
Using java.nio package (Channel-based approach) :- In this approach, you use the FileChannel and ByteBuffer to write data to a file.
Example :–
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption; public class WriteToFileNIOExample { public static void main(String[] args) { String content = "Hello, world!"; Path filePath = Path.of("example.txt");
try (FileChannel channel = FileChannel.open(filePath,StandardOpenOption.WRITE,
StandardOpenOption.CREATE)) { ByteBuffer buffer = ByteBuffer.wrap(content.getBytes()); int bytesWritten = channel.write(buffer); System.out.println("Wrote " + bytesWritten + " bytes to " + filePath); } catch (IOException e) { e.printStackTrace(); } } }
In examples:
2. Delete To File :-
Using the Files class from Java NIO (Java 7 and later) :- You can also use the Files.delete(Path path) method from the java.nio.file package to delete a file.
Example :-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileDeletionExample
{
public static void main(String[] args)
{
String filePath = “path/to/your/file.txt”; // Replace with the path to the file you want to delete Path path = Paths.get(filePath);
try {
Files.delete(path);
System.out.println(“File deleted successfully.”);
}
catch (IOException e)
{
System.err.println(“Failed to delete the file: ” + e.getMessage());
}
}
}
Complete Example of file Handling :-
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
public class FileHandlingExample
{
public static void main(String[] args)
{
// Specify a file name and path
String fileName = “example.txt”;
// Create a new file
try {
File file = new File(fileName);
if (file.createNewFile())
{
System.out.println(“File created: ” + file.getName());
}
else {
System.out.println(“File already exists.”);
}
}
catch (IOException e)
{
System.err.println(“An error occurred while creating the file.”);
e.printStackTrace();
}
// Write data to the file
try {
FileWriter writer = new FileWriter(fileName);
writer.write(“Hello, this is an example of file handling in Java.”);
writer.close();
System.out.println(“Data written to the file.”);
}
catch (IOException e)
{
System.err.println(“An error occurred while writing to the file.”);
e.printStackTrace();
}
// Read data from the file
try {
FileReader reader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
System.out.println(“Reading data from the file:”);
while ((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
}
catch (IOException e)
{
System.err.println(“An error occurred while reading from the file.”);
e.printStackTrace();
}
// Check if the file exists
File checkFile = new File(fileName);
if (checkFile.exists())
{
System.out.println(“The file exists.”);
}
else {
System.out.println(“The file does not exist.”);
}
// Delete the file
if (checkFile.delete())
{
System.out.println(“File deleted: ” + fileName);
}
else {
System.out.println(“Failed to delete the file.”);
}
}
}
Output :-