Java File Create, Read, Write, Delete Example - CRUD Operations

Introduction

File operations such as creating, reading, writing, and deleting files are common tasks in many Java applications. Java provides several classes and methods to perform these operations efficiently. This guide will demonstrate how to create, read, write, and delete files using both the java.io and java.nio.file packages.

Table of Contents

  1. Importing Required Packages
  2. Creating a File
  3. Writing to a File
  4. Reading from a File
  5. Deleting a File
  6. Complete Example
  7. Conclusion

Importing Required Packages

To perform file operations, you need to import the necessary classes from the java.io and java.nio.file packages.

Example

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Arrays;

Creating a File

To create a file, you can use either the File class or the Files.createFile() method from the java.nio.file package.

Example

Using File Class

import java.io.File;
import java.io.IOException;

public class CreateFileExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        try {
            if (file.createNewFile()) {
                System.out.println("File created successfully: " + file.getAbsolutePath());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Files.createFile() Method

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class CreateFileNIOExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
        try {
            Files.createFile(filePath);
            System.out.println("File created successfully: " + filePath.toAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Writing to a File

To write to a file, you can use either the FileWriter and BufferedWriter classes or the Files.write() method from the java.nio.file package.

Example

Using FileWriter and BufferedWriter Classes

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {
    public static void main(String[] args) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt", true))) {
            writer.write("First line\n");
            writer.write("Second line\n");
            writer.write("Third line\n");
            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Files.write() Method

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.io.IOException;
import java.util.List;
import java.util.Arrays;

public class WriteFileNIOExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
        List<String> lines = Arrays.asList("First line", "Second line", "Third line");
        try {
            Files.write(filePath, lines, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Reading from a File

To read from a file, you can use either the FileReader and BufferedReader classes or the Files.readAllLines() method from the java.nio.file package.

Example

Using FileReader and BufferedReader Classes

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Files.readAllLines() Method

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;

public class ReadFileNIOExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
        try {
            List<String> lines = Files.readAllLines(filePath);
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Deleting a File

To delete a file, you can use either the File.delete() method or the Files.deleteIfExists() method from the java.nio.file package.

Example

Using File.delete() Method

import java.io.File;

public class DeleteFileExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        if (file.delete()) {
            System.out.println("File deleted successfully: " + file.getAbsolutePath());
        } else {
            System.out.println("Failed to delete the file.");
        }
    }
}

Using Files.deleteIfExists() Method

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class DeleteFileNIOExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
        try {
            if (Files.deleteIfExists(filePath)) {
                System.out.println("File deleted successfully: " + filePath.toAbsolutePath());
            } else {
                System.out.println("File does not exist.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Complete Example

Here is a complete example demonstrating how to create, write, read, and delete a file using both the java.io and java.nio.file packages with proper exception handling.

FileOperationsExample.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Arrays;

public class FileOperationsExample {
    public static void main(String[] args) {
        // Create a file using File class
        File file = new File("example.txt");
        try {
            if (file.createNewFile()) {
                System.out.println("File created successfully: " + file.getAbsolutePath());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Write to the file using BufferedWriter
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt", true))) {
            writer.write("First line\n");
            writer.write("Second line\n");
            writer.write("Third line\n");
            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Read from the file using BufferedReader
        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Delete the file using File class
        if (file.delete()) {
            System.out.println("File deleted successfully: " + file.getAbsolutePath());
        } else {
            System.out.println("Failed to delete the file.");
        }

        // Create a file using Files.createFile() method
        Path filePath = Paths.get("example.txt");
        try {
            Files.createFile(filePath);
            System.out.println("File created successfully: " + filePath.toAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Write to the file using Files.write() method
        List<String> lines = Arrays.asList("First line", "Second line", "Third line");
        try {
            Files.write(filePath, lines, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Read from the file using Files.readAllLines() method
        try {
            List<String> readLines = Files.readAllLines(filePath);
            for (String line : readLines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Delete the file using Files.deleteIfExists() method
        try {
            if (Files.deleteIfExists(filePath)) {
                System.out.println("File deleted successfully: " + filePath.toAbsolutePath());
            } else {
                System.out.println("File does not exist.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Conclusion

Java provides multiple ways to perform file operations such as creating, reading, writing, and deleting files. By using the java.io and java.nio.file packages, you can efficiently manage file operations in your Java applications. Understanding how to use these methods and handle potential exceptions ensures robust and error-free file handling in your programs.

Comments