Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering Java File Operations with java.io – Creation, Reading, Writing & Deletion

Java File Class

In this tutorial, we explore the java.io.File class and its essential file‑system operations, illustrated with clear examples.

The File class from the java.io package provides a programmatic interface for working with files and directories on the file system. While the newer java.nio.file API offers additional capabilities, this guide focuses on the classic java.io approach.


File and Directory

A file is a named storage location for data. For instance, main.java contains source code for a Java program.

A directory (or folder) is a container that can hold files and other directories—subdirectories. Understanding these concepts is the foundation for manipulating the file system in Java.


Creating a File Object

First, import the class:

import java.io.File;

Then instantiate it with a pathname:

// Creates a File object representing the path
File file = new File("path/to/file.txt");

The File instance is merely an abstract representation; it does not create the physical file on disk.

Note: Instantiating File does not create a file; it only holds the pathname.


Key File Operations

OperationMethodPackage
Create a filecreateNewFile()java.io.File
Read a fileread()java.io.FileReader
Write to a filewrite()java.io.FileWriter
Delete a filedelete()java.io.File

Creating Files

The createNewFile() method attempts to create a new file at the specified path. It returns:

Example: Create a New File

import java.io.File;

public class Main {
    public static void main(String[] args) {
        File file = new File("newFile.txt");
        try {
            boolean created = file.createNewFile();
            if (created) {
                System.out.println("The new file is created.");
            } else {
                System.out.println("The file already exists.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If newFile.txt is absent, the program outputs:

The new file is created.

If it already exists, the output is:

The file already exists.

Reading Files

Reading can be done via subclasses of InputStream or Reader. A common choice is FileReader.

Example: Read a File with FileReader

import java.io.FileReader;

public class Main {
    public static void main(String[] args) {
        char[] buffer = new char[100];
        try {
            FileReader reader = new FileReader("input.txt");
            reader.read(buffer);
            System.out.println("Data in the file:");
            System.out.println(buffer);
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The sample file input.txt contains:

This is a line of text inside the file.

Running the program prints:

Data in the file:
This is a line of text inside the file.

Writing to Files

Writing is typically performed with subclasses of OutputStream or Writer, such as FileWriter.

Example: Write to a File with FileWriter

import java.io.FileWriter;

public class Main {
    public static void main(String[] args) {
        String data = "This is the data in the output file";
        try {
            FileWriter writer = new FileWriter("output.txt");
            writer.write(data);
            System.out.println("Data is written to the file.");
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The resulting output.txt contains:

This is the data in the output file.

Deleting Files

The delete() method removes the specified file or directory. It returns:

Note: Only empty directories can be deleted using delete().

Example: Delete a File

import java.io.File;

public class Main {
    public static void main(String[] args) {
        File file = new File("file.txt");
        boolean deleted = file.delete();
        if (deleted) {
            System.out.println("The File is deleted.");
        } else {
            System.out.println("The File is not deleted.");
        }
    }
}

Output:

The File is deleted.


Java

  1. Mastering Java Anonymous Inner Classes: Definition, Syntax, and Practical Examples
  2. Mastering Java FileInputStream: A Practical Guide with Code Examples
  3. Mastering Java’s ObjectInputStream: A Comprehensive Guide
  4. Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples
  5. Mastering Java BufferedInputStream: Efficient Byte Reading & Advanced Methods
  6. Mastering Java’s PrintStream Class: Print, Println, and Printf Explained
  7. Mastering Java FileReader: Comprehensive Guide & Practical Examples
  8. Mastering Java FileWriter: A Complete Tutorial
  9. Mastering Java BufferedReader: Efficient Character Stream Handling
  10. Java BufferedWriter: Efficient Character I/O Explained