Java File Handling Programs
File Handling in Java In Java, 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? File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it. In simple words, file handling means reading and writing data to a file. Example: // 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! 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: // Creating File using Java Program // Import the File class import java.io.File; import java.io.IOException; public class CreateFile { public static void main(String[] args) { // Creating the File also // Handling Exception 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(); } } } 2. Write to a File We use the FileWriter class along with its write() method in order to write some text to the file. Example: // Writing Files using Java Program // Import the FileWriter class import java.io.FileWriter; import java.io.IOException; public class WriteFile { public static void main(String[] args) { // Writing Text File also // Exception Handling 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(); } } } 3. Read from a File We will use the Scanner class in order to read contents from a file. *Example: * // Reading File using Java Program // Import the File class import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFile { public static void main(String[] args) { // Reading File also // Handling Exception 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(); } } } 4. Delete a File We use the delete() method in order to delete a file. Example: // Deleting File using Java Program 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."); } } } EXAMPLE program for File handling package pratice; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class iofile { public static void main(String[] args) throws IOException { // Specify the directory path File directory = new File("/home/neelakandan/Downloads/neel/subfolder"); // Create the directory and subfolder if they don't exist boolean created = directory.mkdirs(); if (created) { System.out.println("Directory and subfolder created successfully."); } else { System.out.println("Directory and subfolder already exist."); } File note = new File(directory, "note.txt");

File Handling in Java
In Java, 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?
File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it.
In simple words, file handling means reading and writing data to a file.
Example:
// 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!
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:
// Creating File using Java Program
// Import the File class
import java.io.File;
import java.io.IOException;
public class CreateFile
{
public static void main(String[] args)
{
// Creating the File also
// Handling Exception
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();
}
}
}
2. Write to a File
We use the FileWriter class along with its write() method in order to write some text to the file.
Example:
// Writing Files using Java Program
// Import the FileWriter class
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile
{
public static void main(String[] args)
{
// Writing Text File also
// Exception Handling
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();
}
}
}
3. Read from a File
We will use the Scanner class in order to read contents from a file.
*Example:
*
// Reading File using Java Program
// Import the File class
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile
{
public static void main(String[] args)
{
// Reading File also
// Handling Exception
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();
}
}
}
4. Delete a File
We use the delete() method in order to delete a file.
Example:
// Deleting File using Java Program
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.");
}
}
}
EXAMPLE program for File handling
package pratice;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class iofile {
public static void main(String[] args) throws IOException {
// Specify the directory path
File directory = new File("/home/neelakandan/Downloads/neel/subfolder");
// Create the directory and subfolder if they don't exist
boolean created = directory.mkdirs();
if (created) {
System.out.println("Directory and subfolder created successfully.");
} else {
System.out.println("Directory and subfolder already exist.");
}
File note = new File(directory, "note.txt");
boolean fileCreated = note.createNewFile();
if (fileCreated) {
System.out.println("File created successfully.");
} else {
System.out.println("File already exists.");
}
// Writing to the file
try (FileWriter pen = new FileWriter(note); BufferedWriter bPen = new BufferedWriter(pen)) {
bPen.write("The story of Dragon movie starts from School Culturals");
bPen.newLine();
bPen.write("In the next scene, Principal gives talk.");
bPen.flush(); // Ensures data is written to the file
} catch (IOException e) {
e.printStackTrace();
}
// Reading from the file
try (FileReader reader = new FileReader(note)) {
int no_of_space = 1; // Count spaces (approx words)
int no_of_sentences = 0; // Count sentences based on period
int no = reader.read();
while (no != -1) {
System.out.print((char) no);
if ((char) no == ' ')
no_of_space++;
if ((char) no == '.')
no_of_sentences++;
no = reader.read(); // Read the next character
}
System.out.println();
System.out.println("Spaces in the file: " + no_of_space); // Count spaces (approx words)
System.out.println("Sentences in the file: " + no_of_sentences); // Count sentences
} catch (IOException e) {
e.printStackTrace();
}
}
}
OUTPUT:
File already exists.
The story of Dragon movie starts from School Culturals
In the next scene, Principal gives talk.
Spaces in the file: 15
Sentences in the file: 1
1. What is Java file handling?
Java file handling is the way we read from and write to files in Java programs, allowing us to save and retrieve data for tasks like storing information or configuration settings.
2. How do I read data from a file in Java?
To read data from a file in Java, you can use classes like FileReader and BufferedReader, which help you open, read, and close files easily.
3. How can I write data to a file using Java?
Writing data to a file in Java is done using classes like FileWriter and BufferedWriter, which enable you to create, write, and save information to files.
4. What are the common exceptions in Java file handling?
In Java file handling, common exceptions like FileNotFoundException and IOException can occur when files are missing or errors occur while reading or writing data. Handling these exceptions helps make your code more robust.
Reference:https://www.geeksforgeeks.org/file-handling-in-java/