Working with the File System in Java: A Practical Guide
Working with the file system is one of the fundamental tasks in programming. Java provides a powerful and flexible set of tools for this, ranging from the classic java.io package to the modern java.nio.file. In this article, using practical examples, we will cover how to create, read, write, and delete files, as well as work with directories.
1. The File Class: The Foundation of File Operations
The java.io.File class is the basic class for representing a path to a file or directory. It allows you to check existence, create, rename, and delete file system objects.
Creating and Checking File Existence
import java.io.File;import java.io.IOException;
public class FileExample { public static void main(String[] args) { File file = new File("example.txt");
if (file.exists()) { System.out.println("File exists: " + file.getAbsolutePath()); } else { try { if (file.createNewFile()) { System.out.println("File created: " + file.getName()); } } catch (IOException e) { System.err.println("Error creating file: " + e.getMessage()); } }
// Checking properties System.out.println("Readable: " + file.canRead()); System.out.println("Writable: " + file.canWrite()); System.out.println("Size: " + file.length() + " bytes"); }}Working with Directories
File dir = new File("my_directory");
if (dir.mkdir()) { System.out.println("Directory created");}
// Creating nested directoriesFile nestedDir = new File("parent/child/grandchild");if (nestedDir.mkdirs()) { System.out.println("Nested directories created");}
// Getting the list of filesString[] files = dir.list();for (String fileName : files) { System.out.println(fileName);}2. Reading and Writing Files via FileReader/FileWriter
For working with text files, it is convenient to use the FileReader and FileWriter classes. They operate at the character level and support encodings.
Writing to a File
import java.io.FileWriter;import java.io.IOException;
public class WriteExample { public static void main(String[] args) { try (FileWriter writer = new FileWriter("output.txt", true)) { writer.write("Hello, world!"); writer.write("This is the second line."); writer.flush(); System.out.println("Data written successfully"); } catch (IOException e) { System.err.println("Write error: " + e.getMessage()); } }}Note: the second parameter true in the FileWriter constructor enables append mode. If omitted, the file will be overwritten.
Reading from a File
import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;
public class ReadExample { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new FileReader("output.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.err.println("Read error: " + e.getMessage()); } }}Using BufferedReader significantly speeds up reading large files due to buffering.
3. The Modern Approach: java.nio.file (NIO.2)
Starting with Java 7, the java.nio.file package was introduced, which provides more convenient and performant tools for