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.

Feb 22, 20265 views0 likes0 fires
18px

[!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!

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

Continue Learning

31. Generics: Type-Safe Templates

Advanced
12 min

32. Lambda Expressions & Functional Interfaces

Advanced
14 min

33. The Stream API: Functional Data Pipelines

Advanced
14 min
Lesson 10 of 10 in 3. Core APIs & I/O
Previous in 3. Core APIs & I/O
29. Wrapper Classes & Autoboxing
Completed
You finished this lesson → take the quiz
12 questions • 5 min
Next section: 4. Advanced Java & Frameworks
← Back to Java Programming: From Zero to Enterprise
Back to Java Programming: From Zero to EnterpriseAll Categories