File operation

 import java.io.File;

import java.io.FileWriter;

import java.io.FileReader;

import java.io.BufferedReader;

import java.io.IOException;


public class FileOperations {

    public static void main(String[] args) {

        String filePath = "example.txt";


        // Create a file

        createFile(filePath);


        // Write to the file

        writeFile(filePath, "Hello, this is a test file.");


        // Read from the file

        readFile(filePath);


        // Delete the file

        deleteFile(filePath);

    }


    // Method to create a file

    public static void createFile(String filePath) {

        try {

            File file = new File(filePath);

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

        }

    }


    // Method to write to a file

    public static void writeFile(String filePath, String content) {

        try {

            FileWriter writer = new FileWriter(filePath);

            writer.write(content);

            writer.close();

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

        } catch (IOException e) {

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

            e.printStackTrace();

        }

    }


    // Method to read from a file

    public static void readFile(String filePath) {

        try {

            FileReader reader = new FileReader(filePath);

            BufferedReader bufferedReader = new BufferedReader(reader);

            String line;

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

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

                System.out.println(line);

            }

            bufferedReader.close();

        } catch (IOException e) {

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

            e.printStackTrace();

        }

    }


    // Method to delete a file

    public static void deleteFile(String filePath) {

        File file = new File(filePath);

        if (file.delete()) {

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

        } else {

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

        }

    }

}







Comments

Popular posts from this blog

Product calculation