Java Files

Introduction to Java File Handling

File handling is a critical part of almost any application. Whether you need to read configuration data, write log files, or process user-uploaded content, interacting with the file system is a fundamental skill for a Java developer.

Java provides a rich set of APIs for file I/O (Input/Output).


The java.io.File Class

The cornerstone of file handling in older Java versions is the java.io.File class. It's important to understand that an object of the File class does not represent the content of a file itself, but rather the path to a file or directory on the file system.

You can use a File object to perform operations like:

Creating a File Object

import java.io.File;

public class Main { public static void main(String[] args) { // Create a File object representing a path File myFile = new File("my-first-file.txt"); if (myFile.exists()) { System.out.println("File name: " + myFile.getName()); System.out.println("Absolute path: " + myFile.getAbsolutePath()); System.out.println("Writeable: " + myFile.canWrite()); System.out.println("Readable: " + myFile.canRead()); System.out.println("File size in bytes: " + myFile.length()); } else { System.out.println("The file does not exist."); } } }


Streams: Reading and Writing Data

To read or write the content of a file, Java uses streams. A stream is a sequence of data.

For handling text files, Java provides Reader and Writer classes, which work with characters instead of bytes.


The Modern API: java.nio.file

Since Java 7, a new, more powerful file I/O library was introduced: the NIO.2 (New I/O) API, located in the java.nio.file package. It was designed to overcome many of the limitations of the original java.io.File class.

Key classes in the new API include:

For new projects, it is generally recommended to use the java.nio.file API as it provides better error handling and more features. In the following chapters, we will show examples using both the traditional java.io and the modern java.nio approaches.


Exercise

?

What does an object of the `java.io.File` class represent?