DEV Community

Cover image for Java File Handling Programs
Neelakandan R
Neelakandan R

Posted on

7 3 3 3 3

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!");
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

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.");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

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 file_handling {
    public static void main(String[] args) throws IOException {
        File note = new File("/home/neelakandan/Downloads/neels/ayan/note");
        note.mkdir();

        File disc = new File(note, "letter.txt");
        disc.createNewFile();

        FileWriter pen = new FileWriter(disc);
        BufferedWriter bPen = new BufferedWriter(pen);
        bPen.write("The story of Dragon movie starts from School Culturals.");
        bPen.write("In the next scene, Principal gives talk.");
        bPen.flush();
        bPen.close();

        FileReader reader = new FileReader(disc);
        int letter = reader.read();
        int no_of_space = 1;
        int no_of_sentences = 0;

        while (letter != -1) {
            System.out.print((char) letter);
            if ((char) letter == ' ')
                no_of_space++;
            if ((char) letter == '.')
                no_of_sentences++;
            letter = reader.read();
        }
        System.out.println();
        System.out.println("no_of_word = " + no_of_space);
        System.out.println("no_of_dot = " + no_of_sentences);
    }

}

Enter fullscreen mode Exit fullscreen mode

Output:The story of Dragon movie starts from School Culturals.In the next scene, Principal gives talk.
no_of_word = 15
no_of_dot = 2

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();
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

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/

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong ยท web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video ๐ŸŒถ๏ธ๐Ÿ”ฅ

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. โค๏ธ