n Java, we use "Streams" to move data. Imagine a water pipe: data flows from your program into a file, or from a file into your program.
The Modern Way: Files and Paths
Java has several ways to handle files. The oldest way (using File) is a bit clunky. Modern Java (since version 7/8) uses the java.nio.file package, which is much easier and more powerful.
We will use:
Paths.get(): To find the file location.Files.writeString(): To save text easily.Files.readString(): To pull text back into our program.
The Code Example:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class FileIODemo {
public static void main(String[] args) {
String fileName = "myNote.txt";
String contentToWrite = "Hello! This is a secret message stored in a file.\nJava is awesome!";
// 1. Defining the Path
Path path = Paths.get(fileName);
try {
// 2. Writing to the file (This creates the file if it doesn't exist)
Files.writeString(path, contentToWrite);
System.out.println("Success: File written to " + path.toAbsolutePath());
System.out.println("--- Reading back from the file ---");
// 3. Reading from the file
String readContent = Files.readString(path);
// Displaying what we found
System.out.println("File Content:\n" + readContent);
} catch (IOException e) {
// File operations can fail (no permission, disk full), so we NEED try-catch
System.out.println("An error occurred: " + e.getMessage());
}
}
}Expected Output:
Success: File written to C:\Users\Current\Project\myNote.txt
--- Reading back from the file ---
File Content:
Hello! This is a secret message stored in a file.
Java is awesome!File I/O is the first step toward building real software. You use it for:
Settings/Preferences: Saving a user's "Dark Mode" choice.
Logging: Keeping a record of when an error occurred.
Data Storage: Saving a high score in a game or a list of tasks in a To-Do app.
Important: Always wrap File I/O in a try-catch block. Unlike some other errors, Java forces you to handle
IOExceptionbecause the computer's file system is unpredictable!