Essentials of Java File I/O Operations

Creating Directories and Files

To establish new storage locasions, the File class provides methods for directory and file generation. Attempting to create a directory involves calling mkdir(), while creating an empty file utilizes createNewFile().

package com.example.io;

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

public class DirectoryCreator {
    
    public static void main(String[] args) throws IOException {
        String baseDirectory = "C:\\Users\\Dev\\Data";
        File targetDir = new File(baseDirectory);
        boolean isDirCreated = targetDir.mkdir();
        
        if (isDirCreated) {
            System.out.println("Target directory established.");
            File targetFile = new File(targetDir, "output_document.txt");
            boolean isFileCreated = targetFile.createNewFile();
            
            if (isFileCreated) {
                System.out.println("Target file established successfully.");
            } else {
                System.out.println("Failed to create file.");
            }
        } else {
            System.out.println("Directory creation failed.");
        }
    }
}

Deleting Files and Folders

Removing items from the disk requires specific logic. If a directory contains nested files or subdirectories, standard deletion may fail. It is safer to ensure a directory is empty before removing it.

package com.example.io;

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

public class FileDeleter {
    
    public static void main(String[] args) throws IOException {
        File targetFile = new File("C:\\Users\\Dev\\Data\\output_document.txt");
        
        if (targetFile.exists()) {
            boolean success = targetFile.delete();
            if (success) {
                System.out.println("File removed.");
            } else {
                System.out.println("Removal failed.");
            }
        }
        
        File targetDir = new File("C:\\Users\\Dev\\Data");
        if (targetDir.exists()) {
            boolean dirSuccess = targetDir.delete();
            if (dirSuccess) {
                System.out.println("Directory removed.");
            } else {
                System.out.println("Directory removal failed.");
            }
        }
    }
}

Traversing Directory Contents

Enumerating the contents of a folder is achieved using listFiles(). This returns an array of File objects representing every entry with in the specified path.

package com.example.io;

import java.io.File;

public class DirectoryTraverser {
    
    public static void main(String[] args) {
        File sourceDir = new File("D:\\Sources\\Docs");
        File[] entries = sourceDir.listFiles();
        
        if (entries != null) {
            for (File entry : entries) {
                System.out.println(entry.getPath());
            }
        }
    }
}

Reading Data from Files

Character streams (Reader) are efficient for text processing. Two common patterns exist: reading into a buffer block-wise or reading character-by-character in a loop.

Bulk Block Reading

package com.example.io;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;

public class FileReaderBulk {
    
    public static void main(String[] args) throws Exception {
        File input = new File("D:\\sources\\cxy.txt");
        try (Reader reader = new FileReader(input)) {
            char[] buffer = new char[1024];
            int bytesRead = reader.read(buffer);
            System.out.println("Content:\n" + new String(buffer, 0, bytesRead));
        }
    }
}

Incremental Character Reading

package com.example.io;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;

public class FileReaderStream {
    
    public static void main(String[] args) throws Exception {
        File input = new File("D:\\sources\\cxy.txt");
        try (Reader reader = new FileReader(input)) {
            char[] buffer = new char[1024];
            int index = 0;
            int charRead;
            
            while ((charRead = reader.read()) != -1) {
                if (index >= buffer.length) {
                    char[] temp = new char[index * 2];
                    System.arraycopy(buffer, 0, temp, 0, index);
                    buffer = temp;
                }
                buffer[index++] = (char) charRead;
            }
            System.out.println(new String(buffer, 0, index));
        }
    }
}

Writing Data to Files

Output streams manage data writing. The constructor determines whether existing data should be overwritten or appended.

Overwriting Content

Using the default constructor clears previous data before writing new bytes.

package com.example.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class FileWriterOverwrite {
    
    public static void main(String[] args) throws Exception {
        File outputLoc = new File("D:\\Backups\\log.txt");
        try (OutputStream writer = new FileOutputStream(outputLoc)) {
            String message = "System updated successfully at startup.";
            writer.write(message.getBytes());
        }
    }
}

Appending Content

By passing true to the constructor, data is written to the end of the existing file with out erasing prior content.

package com.example.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class FileWriterAppend {
    
    public static void main(String[] args) throws Exception {
        File outputLoc = new File("D:\\Backups\\log.txt");
        try (OutputStream writer = new FileOutputStream(outputLoc, true)) {
            String logEntry = "Additional system update note here.";
            writer.write(logEntry.getBytes());
        }
    }
}

Tags: java File I/O programming Developer Guide

Posted on Fri, 15 May 2026 17:46:05 +0000 by samtwilliams