Java File Handling

Working with files is a fundamental part of many programming tasks. In Java, there are several classes and methods that you can use to work with files. In this tutorial, we will cover some of the basic file handling operations in Java. Let’s give this note a go:

Creating a File

To create a new file in Java, you can use the File class. The File class provides a constructor that takes a file path as a parameter. Here’s an example:

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

This creates a new File object called file that represents a file with the name “filename.txt”. Note that this doesn’t actually create a file on the disk, it just creates a Java object that represents a file.

To create the file on the disk, you can call the createNewFile() method on the File object:

if (file.createNewFile()) {
    System.out.println("File created successfully");
} else {
    System.out.println("File already exists");
}

The createNewFile() method returns true if the file was created successfully, and false if the file already exists.

Writing to a File

To write to a file, you can use the FileWriter class. The FileWriter class provides a constructor that takes a file path as a parameter. Here’s an example:

FileWriter writer = new FileWriter("filename.txt");

This creates a new FileWriter object called writer that can be used to write to the file with the name “filename.txt”.

To write data to the file, you can call the write() method on the FileWriter object:

writer.write("Hello, world!");

This writes the string “Hello, world!” to the file. Note that this overwrites any existing data in the file. To append data to the end of the file, you can use the append() method:

writer.append("This is some more text");

Reading from a File

To read from a file, you can use the FileReader class. The FileReader class provides a constructor that takes a file path as a parameter. Here’s an example:

FileReader reader = new FileReader("filename.txt");

This creates a new FileReader object called reader that can be used to read from the file with the name “filename.txt”.

To read data from the file, you can call the read() method on the FileReader object:

int data = reader.read();
while (data != -1) {
    System.out.print((char) data);
    data = reader.read();
}

This reads one character at a time from the file and prints it to the console. The read() method returns -1 when the end of the file is reached.

Closing a File

After you are finished reading from or writing to a file, you should close the file. To close a file, you can call the close() method on the file object:

writer.close();
reader.close();

This closes the FileWriter and FileReader objects, and releases any resources associated with them.

A complete example of creating, reading, and writing to a file in Java:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileExample {
    public static void main(String[] args) {
        // Create a new file
        File file = new File("example.txt");
        try {
            file.createNewFile();
        } catch (IOException e) {
            System.out.println("Error creating file: " + file.getAbsolutePath());
            e.printStackTrace();
        }

        // Write to the file
        try {
            FileWriter writer = new FileWriter(file);
            writer.write("Hello, world!\n");
            writer.write("This is an example file.\n");
            writer.close();
        } catch (IOException e) {
            System.out.println("Error writing to file: " + file.getAbsolutePath());
            e.printStackTrace();
        }

        // Read from the file
        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (IOException e) {
            System.out.println("Error reading file: " + file.getAbsolutePath());
            e.printStackTrace();
        }
    }
}

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author