allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œIf you want to lift yourself up, lift up someone else.โ€
[Booker T. Washington (1856โ€“1915) โ€“ American educator and civil rights leader]


Reading and Writing


17.1.1 Why File I/O Matters

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.



17.1.2 Basic File Reading and Writing

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).



17.1.3 Mini Lab: Basic Text File I/O

Below is a practical starter lab โ€” write to a text file, then read it back.

java
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileIOMiniLab { public static void main(String[] args) { // 1๏ธโƒฃ Writing to a file try { FileWriter writer = new FileWriter("output.txt"); writer.write("Hello, this is Java File I/O!\n"); writer.write("Writing a second line.\n"); writer.close(); System.out.println("โœ… Writing done."); } catch (IOException e) { System.out.println("Error writing file: " + e.getMessage()); } // 2๏ธโƒฃ Reading from the file try { FileReader reader = new FileReader("output.txt"); int c; System.out.println("๐Ÿ“– Reading file:"); while ((c = reader.read()) != -1) { System.out.print((char) c); } reader.close(); } catch (IOException e) { System.out.println("Error reading file: " + e.getMessage()); } } }

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.