← Back to Home

Module 4: File I/O

Module Overview

File Input/Output (I/O) operations are essential for working with data in Java applications. In this module, you'll learn how to read from and write to files, handle different file formats, and manage file resources properly.

Learning Objectives

File I/O in Java Explained

File Input/Output (I/O) operations are essential for working with external data sources in Java applications. These operations allow you to read data from files and write data to files.

Basic File I/O Operations

Reading Text Files

Java provides several ways to read text files. One common approach uses FileReader and BufferedReader:

FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String fileContents = "";

String line = bufferedReader.readLine();  
while (line != null) {
    fileContents += line + "\n";
    line = bufferedReader.readLine();
}

bufferedReader.close();

Writing Text Files

For writing to text files, you can use FileWriter and BufferedWriter:

FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

bufferedWriter.write("Hello World!");

bufferedWriter.close();

Working with Binary Files

For binary files or when you need to work with any file type, use FileInputStream and FileOutputStream:

FileInputStream inStream = new FileInputStream(inFile);
byte[] buffer = new byte[256];
int bytesRead = inStream.read(buffer);

while (bytesRead > 0) {
    // Process bytes
    bytesRead = inStream.read(buffer);
}

inStream.close();

Exception Handling

File operations require proper exception handling:

Key Topics

Java File Operations

  • File operations
    • Reading files
    • Writing files
    • File paths and directories
    • File permissions
  • Streams and readers
    • FileInputStream/FileOutputStream
    • BufferedReader/BufferedWriter
    • Character streams
    • Byte streams
  • Resource management
    • Try-with-resources
    • Exception handling
    • File closing
    • Resource cleanup

Resources

Practice Exercises

  • Read and write text files
  • Handle binary files
  • Process CSV files
  • Implement file operations with proper resource management

Next Steps

After completing this module:

  1. Complete the practice exercises above
  2. Review the additional resources for deeper understanding
  3. Prepare for the Sprint Challenge