Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
3. Core APIs & I/O
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

30. Basic File I/O

Interacting with the operating system: Creating, Reading, and Writing files.

Java Programming: From Zero to Enterprise
3. Core APIs & I/O
February 22, 2026
64
A

[!NOTE] Until now, all of our application data existed exclusively in RAM. If we restarted the program, all variables vanished. To permanently persist data (without diving into complex SQL databases), we write it to hard disk files.

The java.io.File class allows us to create and read files from the host Operating System.

Creating and Writing to a File

When writing a file, we utilize the FileWriter class. Remember our lesson on the try-catch block? File operations touch external hardware, meaning they are highly prone to crashing (e.g., hard drive is full, lacking admin permission). Therefore, Java enforces a try-catch block for all I/O operations via Checked Exceptions.

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

public class WriteExample {
  public static void main(String[] args) {
    
    // Explicitly required try/catch!
    try {
      // 1. Target the file (it will create it if it doesn't exist!)
      FileWriter myWriter = new FileWriter("filename.txt");
      
      // 2. Write the string payload
      myWriter.write("Java File I/O is easier than you think. Logging data to disk...");
      
      // 3. MANDATORY: Close the stream! If you forget this, the data may never actually flush to the disk!
      myWriter.close();
      
      System.out.println("Successfully wrote to the file.");
      
    } catch (IOException e) {
      System.out.println("An error occurred. Check permission restrictions.");
      e.printStackTrace();
    }
  }
}

Reading from a File

To read from a file, we can hook our good friend the Scanner up to a File Object, rather than hooking it up to System.in (the keyboard).

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadExample {
  public static void main(String[] args) {
    
    // Required to catch specific non-existent files
    try {
      // 1. Establish the target
      File myObj = new File("filename.txt");
      
      // 2. Inform the Scanner to read the File, not the Keyboard!
      Scanner myReader = new Scanner(myObj);
      
      // 3. Loop through every line until the end of the file is reached
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
      }
      
      // 4. Free up memory!
      myReader.close();
      
    } catch (FileNotFoundException e) {
      System.out.println("The requested file was completely missing!");
    }
  }
}

[!TIP] Getting File Meta Info: Before reading, you can execute myObj.exists() to check if it's there safely. You can also run myObj.length() to get the exact file size in bytes to prevent attempting to load a 100GB text file into a 2GB RAM container!

Prefer try-with-resources for File Work

Files, streams, readers, and writers must be closed. Modern Java gives you try-with-resources, which closes resources automatically even when an exception happens.

Writing Safely

Path path = Path.of("notes.txt");

try {
    Files.writeString(path, "Learning Java File I/O");
} catch (IOException e) {
    System.out.println("Could not write file: " + e.getMessage());
}

Reading Safely

Path path = Path.of("notes.txt");

try {
    String content = Files.readString(path);
    System.out.println(content);
} catch (IOException e) {
    System.out.println("Could not read file: " + e.getMessage());
}

The java.nio.file.Files API is often more convenient for common file tasks than older low-level classes.

Before Reading Large Files

Path path = Path.of("large-log.txt");
long size = Files.size(path);

if (size < 5_000_000) {
    String content = Files.readString(path);
}

Common Mistakes

  • Forgetting to close readers or writers.
  • Reading huge files fully into memory without checking size.
  • Hardcoding file paths that only work on one machine.
  • Ignoring character encoding when handling user-visible text.

Mini Practice

Write three lines to a text file, read them back, and print only lines that contain the word Java. Then try reading a missing file and handle the error cleanly.

Practice Lab: Write and Read Study Notes

Persist simple text to disk, then read it back safely.

  1. Create a file path named study-notes.txt.
  2. Write three lines about what you learned in Java.
  3. Read the file back line by line.
  4. Print only lines containing the word Java.
  5. Try reading a missing file and handle the error cleanly.

Goal: Practice basic persistence, checked exceptions, and safe file reading.

Revision Checkpoint

  • File I/O: Moves data between program memory and disk.
  • Checked exceptions: File operations often require handling IOException.
  • Close resources: Use try-with-resources where possible.
  • Files API: Convenient for common read/write tasks.
  • Large files: Avoid reading huge files fully into memory without checking size.

Before the quiz: Explain why closing or flushing a writer matters.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: File IO
12 questions5 min
Lesson 10 of 10 in 3. Core APIs & I/O
Previous in 3. Core APIs & I/O
29. Wrapper Classes & Autoboxing
Next section: 4. Advanced Java & Frameworks
31. Generics: Type-Safe Templates
4. Advanced Java & Frameworks
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories