Reading and Writing
In real-world Java apps โ especially web servers, APIs, backend tools โ you often deal with files:
Saving logs
Exporting CSV or JSON
Reading configuration files
Generating reports
File I/O (Input/Output) means your program reads data from files and writes data to files stored on disk.
Unlike reading user input from the console, File I/O must handle:
Persistent data: files live on disk after the program stops.
Permissions: the program needs permission to read/write.
Exceptions: what if the file is missing? Or locked? Or corrupted?
Java provides powerful, flexible classes to make this easy and safe.
Java has two main ways for basic file handling:
1๏ธโฃ FileReader
& FileWriter
: character-based (good for text).
2๏ธโฃ FileInputStream
& FileOutputStream
: byte-based (good for binary files like images).
For simple text, FileReader
and FileWriter
are the classic starting point.
โ Key Concept:
FileReader
reads character by character.
FileWriter
writes character by character.
Theyโre fine for small files but can be inefficient alone โ thatโs where Buffered I/O comes in (weโll cover that in 17.2).
Below is a practical starter lab โ write to a text file, then read it back.
How this works:
FileWriter
opens (or creates) output.txt
and writes lines.
Always close()
the writer โ it flushes remaining data.
FileReader
opens the file and reads one char at a time until EOF (-1
).
โ
Try running it: youโll see the output.txt
file appear in your project folder.