FileOperationsProgram

 import java.io.File;

import java.io.FileWriter;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;


public class FileOperationsProgram{

    public static void main(String[] args) {

        File file = new File("example.txt");


        // Create a file

        try{

            if (file.createNewFile()) {

                System.out.println("File created: " + file.getName());

            } else {

                System.out.println("File already exists.");

            }

        } catch (IOException e) {

            System.out.println("An error occurred while creating the file.");

            e.printStackTrace();

            return; // Exit if file creation fails

        }


        // Write to the file

        try (FileWriter fw = new FileWriter(file)) {

            fw.write(" This is a test file.");

            System.out.println("Successfully wrote to the file.");

        } catch (IOException e) {

            System.out.println("An error occurred while writing to the file.");

            e.printStackTrace();

            return; // Exit if file writing fails

        }


        // Read from the file

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {

            String line;

            System.out.println("Reading from the file:");

            while ((line = br.readLine()) != null) {

                System.out.println(line);

            }

        } catch (IOException e) {

            System.out.println("An error occurred while reading from the file.");

            e.printStackTrace();

        }


        // Delete the file

        if (file.delete()) {

            System.out.println("Deleted the file: " + file.getName());

        } else {

            System.out.println("Failed to delete the file.");

}

}

}

Output:

File created: example.txt

Successfully wrote to the file.

Read from the file:

This is a test file.

Deleted the file:  example.txt

Comments