COMPUTER SCIENCE - SENIOR 5
UNIT 12
IO AND JAVA
Key Unit Competency
To be able to use Stream, Reader and Writer in Java
Topics to be Covered Learning Objectives
• 12.1 Introduction to IO Streams • Understand Java IO stream concepts
• 12.2 InputStream, OutputStream & Input Methods • Read user input from keyboard
• 12.3 FileStreams • Use Scanner, BufferedReader, DataInputStream
• 12.4 Readers and Writers • Read and write data to files
• 12.5 Character Streams • Work with Reader, Writer & Character Streams
12.1 Introduction to IO Streams
Stream
Definition 1: A stream is a sequence of data (bytes or characters) that flows from an input source
(keyboard, file, network) to an output destination (screen, file, network).
Definition 2: A stream is a Java abstraction that represents a continuous flow of data between a
program and an external device, hiding the complexity of the underlying data source or destination.
12.1.1 Types of Streams
Java provides two main categories of streams:
Stream Type Data Unit Base Classes Best Used For
Byte Stream 8-bit (1 byte) InputStream / OutputStream Images, audio, binary files
Character Stream 16-bit (1 char) Reader / Writer Text files, Unicode text
12.1.2 Standard Java IO Objects
Three IO objects are available automatically in every Java program:
Object Type Connected To Purpose
[Link] InputStream Keyboard Read input data
[Link] OutputStream Screen (monitor) Display normal output
[Link] OutputStream Screen (monitor) Display error messages
12.1.3 InputStream vs OutputStream
InputStream
Definition 1: InputStream is an abstract class representing a source from which byte data is read into
a Java program — data flows INTO the program.
Definition 2: InputStream is Java's base class for reading bytes from any source (keyboard, file,
network). Its key method is read(), which returns one byte at a time.
OutputStream
Definition 1: OutputStream is an abstract class representing a destination to which byte data is
written from a Java program — data flows OUT of the program.
Definition 2: OutputStream is Java's base class for writing bytes to any destination (screen, file,
network). Its key method is write(), which sends one byte at a time.
12.2 InputStream, OutputStream and Input Methods
12.2.1 OutputStream - Displaying Output
Java uses output streams to write data to a destination such as a screen or file.
Method What It Does Example
[Link]() Prints without moving to a [Link]("Hi");
new line
[Link]() Prints and moves to a new [Link]("Hi");
line
Example 1: Basic Output Program
class FirstProgram {
public static void main(String[] args) {
[Link]("Good morning Sir");
[Link]("Welcome to Java programming");
}
}
// OUTPUT:
// Good morning Sir
// Welcome to Java programming
12.2.2 InputStream - Reading Input from User
Java uses input streams to read data entered by the user. There are three popular approaches:
a) Scanner Class
Scanner Class
Definition 1: The Scanner class ([Link]) is a predefined Java class that provides easy-
to-use methods for reading different data types (int, double, String) from the keyboard.
Definition 2: Scanner is a text-parsing tool that reads input from the keyboard and converts it to the
required data type — it is the simplest and most common way to get user input in Java.
Step 1 - Import the Scanner class:
Importing Scanner
import [Link]; // import Scanner class only
// OR
import [Link].*; // import all [Link] classes
Step 2 - Create a Scanner object and read input:
Scanner Methods - Reference Table
Scanner sc = new Scanner([Link]);
int n = [Link](); // reads integer e.g. 55
double d = [Link](); // reads decimal e.g. 3.14
float f = [Link](); // reads float
long l = [Link](); // reads long integer
String word = [Link](); // reads one word
String line = [Link](); // reads full line
boolean b = [Link](); // reads true or false
Example 2: Reading Integer and Double with Scanner
import [Link];
class ReadNumbers {
public static void main(String[] args) {
Scanner s1 = new Scanner([Link]);
[Link]("Enter an integer:");
int n = [Link]();
[Link]("Enter a decimal number:");
double db = [Link]();
[Link]("Integer : " + n);
[Link]("Double : " + db);
}
}
// SAMPLE OUTPUT:
// Enter an integer: 55
// Enter a decimal number: 123.55
// Integer : 55
// Double : 123.55
Advantage of Scanner
Easy to use - has a dedicated method for each data type (nextInt(), nextDouble(), etc.). Ideal for
beginners.
Disadvantage of Scanner
Reading methods are not synchronized - may cause problems when used in programs with multiple
threads running at the same time.
b) BufferedReader Class
BufferedReader
Definition 1: BufferedReader is a Java class that reads text from a character-based input stream
efficiently by storing input in a buffer and reading it line by line using readLine().
Definition 2: BufferedReader wraps an InputStreamReader to convert keyboard byte input into
text, then stores the text in a buffer for faster, more efficient processing.
Example 3: Adding Two Numbers with BufferedReader
import [Link];
import [Link];
class AddNumbers {
public static void main(String args[]) throws Exception {
InputStreamReader is = new InputStreamReader([Link]);
BufferedReader br = new BufferedReader(is);
[Link]("Enter first number:");
int a = [Link]([Link]()); // readLine() returns
String
// parseInt() converts
to int
[Link]("Enter second number:");
int b = [Link]([Link]());
int sum = a + b;
[Link]("Sum is: " + sum);
}
}
// SAMPLE OUTPUT:
// Enter first number: 12
// Enter second number: 35
// Sum is: 47
📝 Important Note
BufferedReader's readLine() always returns a String. Use [Link]() to convert to int, or
[Link]() to convert to double.
Advantage of BufferedReader
Input is buffered for efficient reading — faster when reading large amounts of text.
Disadvantages of BufferedReader
The wrapping code is longer and harder to remember compared to Scanner.
c) DataInputStream
DataInputStream
Definition 1: DataInputStream is a Java class that wraps [Link] (a byte stream) to allow
reading of text lines from the keyboard using the readLine() method.
Definition 2: DataInputStream reads byte-based data from the keyboard line by line, returning
each line as a String which must then be converted to the appropriate data type.
Example 4: Comparing Two Numbers with DataInputStream
import [Link].*;
public class CompareNumbers {
public static void main(String args[]) throws IOException {
try (DataInputStream dis = new DataInputStream([Link])) {
[Link]("Enter your name:");
String name = [Link]();
[Link]("Hello, " + name + "!");
[Link]("Enter a whole number:");
int x = [Link]([Link]());
[Link]("Enter a decimal value:");
double y = [Link]([Link]());
if (x > y)
[Link](x + " is greater than " + y);
else
[Link](x + " is less than " + y);
}
}
}
// SAMPLE OUTPUT:
// Enter your name: UWERA
// Hello, UWERA!
// Enter a whole number: 12
// Enter a decimal value: 15.5
// 12 is less than 15.5
12.3 FileStreams
FileStreams allow Java programs to read data from files and write data to files stored on the computer's
disk.
12.3.1 FileInputStream - Reading from a File
📌 FileInputStream
Definition 1: FileInputStream is a Java class used to read raw byte data from a file on disk,
opening a connection to the file and reading one byte at a time.
Definition 2: FileInputStream connects a Java program to a file stored on the computer, allowing
the program to read the file's contents byte by byte until the end of the file is reached.
Creating a FileInputStream - two ways:
💻 Creating FileInputStream
// Method 1: Provide the file path as a String
InputStream f = new FileInputStream("C:/java/[Link]");
// Method 2: Use a File object
File myFile = new File("C:/java/[Link]");
InputStream f = new FileInputStream(myFile);
Useful FileInputStream Methods:
Method What It Does
read() Reads one byte; returns -1 when end of file is reached
read(byte[] r) Reads multiple bytes into a byte array
available() Returns the number of bytes still available to read
close() Closes the file and frees system resources
Example 5: Reading First Character from a File
import [Link];
public class ReadFile {
public static void main(String args[]) {
try {
// Open file for reading
FileInputStream n = new FileInputStream("D:\\[Link]");
int i = [Link](); // reads one byte
[Link]((char) i); // cast byte to character for display
[Link](); // always close after reading
} catch(Exception e) {
[Link](e);
}
}
}
// If [Link] contains: Hello Programmers.
// OUTPUT: H
⚠️ Important
The file must already exist at the specified path before running this program. If it does not exist, Java
throws a FileNotFoundException.
12.3.2 FileOutputStream - Writing to a File
📌 FileOutputStream
Definition 1: FileOutputStream is a Java class used to write raw byte data to a file. It automatically
creates the file if it does not already exist before writing to it.
Definition 2: FileOutputStream opens a connection from a Java program to a file on disk, allowing
the program to write data byte by byte - creating the file if needed.
Creating a FileOutputStream - two ways:
Creating FileOutputStream
// Method 1: Provide the file path as a String
OutputStream f = new FileOutputStream("C:/java/[Link]");
// Method 2: Use a File object
File myFile = new File("C:/java/[Link]");
OutputStream f = new FileOutputStream(myFile);
Useful FileOutputStream Methods:
Method What It Does
write(int w) Writes a single byte to the file
write(byte[] w) Writes a whole byte array to the file
close() Closes the file and frees system resources
💻 Example 6: Writing Text to a File with FileOutputStream
import [Link];
public class WriteToFile {
public static void main(String[] args) {
try (FileOutputStream fout = new FileOutputStream("[Link]")) {
String s = "I am writing to a file using Java.";
byte b[] = [Link](); // convert String to byte array
[Link](b); // write all bytes to the file
} catch(Exception e) {
[Link](e);
}
[Link]("File written successfully!");
}
}
// OUTPUT on screen: File written successfully!
// File '[Link]' now contains: I am writing to a file using Java.
12.4 Readers and Writers
Readers and Writers are character-based alternatives to InputStream and OutputStream. While
streams handle raw bytes, Readers and Writers handle text characters — making them ideal for
reading and writing text files.
12.4.1 Reader
📌 Reader
Definition 1: Reader ([Link]) is an abstract Java class that serves as the base for all
character-based input classes. It reads text data one character at a time from a source such as
a file or keyboard.
Definition 2: Reader is the character-stream equivalent of InputStream — instead of bytes, it
processes 16-bit Unicode characters, making it suitable for reading text in any language.
Common Reader subclasses:
• FileReader - reads characters directly from a text file
• BufferedReader - reads characters efficiently using a buffer; supports readLine()
• InputStreamReader - converts a byte-based stream into a character-based Reader
• StringReader - reads characters from a String object in memory
💻 Example 7: Reading All Characters from a File with FileReader
import [Link].*;
public class ReadFileChars {
public static void main(String[] args) throws Exception {
Reader reader = new FileReader("c:\\data\\[Link]");
int data = [Link](); // reads one character at a time
while (data != -1) { // -1 signals end of file
char ch = (char) data;
[Link](ch);
data = [Link]();
}
[Link](); // always close when done
}
}
// Reads and prints every character in [Link]
You can also convert an InputStream into a Reader using InputStreamReader:
💻 Combining InputStream with Reader
// Wrap a byte-based InputStream to create a character-based Reader
InputStream inputStream = new FileInputStream("[Link]");
Reader reader = new InputStreamReader(inputStream);
12.4.2 Writer
Writer
Definition 1: Writer ([Link]) is an abstract Java class that serves as the base for all
character-based output classes. It writes text data one character at a time to a destination
such as a file.
Definition 2: Writer is the character-stream equivalent of OutputStream - it sends 16-bit
Unicode characters to a destination, making it suitable for writing text in any language.
Common Writer subclasses:
• FileWriter - writes characters directly to a text file
• BufferedWriter - writes characters efficiently using a buffer
• PrintWriter - writes formatted text; supports println()
• OutputStreamWriter - converts a character stream into a byte-based OutputStream
Example 8: Writing to a File with FileWriter
import [Link].*;
public class WriteChars {
public static void main(String[] args) throws Exception {
Writer writer = new FileWriter("c:\\data\\[Link]");
[Link]("Hello World from Java Writer!");
[Link](); // always close to save the file
}
}
// Creates [Link] with: Hello World from Java Writer!
12.4.3 Buffered Reading and Writing
Why Use Buffering?
Reading or writing one character at a time is slow. Buffering collects many characters at once
and processes them together - this is much faster, especially for large files.
Example 9: Buffered Reader and Writer
import [Link].*;
// Buffered reading from a file
Reader reader = new BufferedReader(new FileReader("[Link]"));
// Buffered writing to a file
Writer writer = new BufferedWriter(new FileWriter("[Link]"));
// Reading lines one at a time with BufferedReader
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
12.5 Character Streams
Character Stream
Definition 1: A character stream in Java handles 16-bit Unicode characters for input and
output, making it the correct choice for reading and writing text data in any language.
Definition 2: Character streams are Java IO classes (subclasses of Reader and Writer) that
process text 2 bytes (one character) at a time, supporting full Unicode to handle all
international characters.
Key comparison between Byte Streams and Character Streams:
Feature Byte Stream Character Stream
Data unit 1 byte (8-bit) 1 character (16-bit Unicode)
Base classes InputStream / OutputStream Reader / Writer
File classes FileInputStream / FileReader / FileWriter
FileOutputStream
Best for Binary data (images, audio) Text files
Example 10: Writing Text with FileWriter
import [Link];
public class FileWriterExample {
public static void main(String args[]) {
try {
FileWriter fw = new FileWriter("D:\\[Link]");
[Link]("Welcome to Java Lesson 12.");
[Link]();
} catch(Exception e) {
[Link](e);
}
[Link]("Success...");
}
}
// OUTPUT on screen: Success...
// File '[Link]' now contains: Welcome to Java Lesson 12.
12.5.1 Standard Streams
Java provides three standard streams available in every program:
Standard Stream Java Object Connected To Use
Standard Input [Link] Keyboard Read user input
Standard Output [Link] Screen Display results
Standard Error [Link] Screen Display error messages
12.5.2 InputStreamReader
InputStreamReader
Definition 1: InputStreamReader ([Link]) is a bridge class that
converts a byte-based InputStream into a character-based Reader, allowing text characters
to be read from a byte source.
Definition 2: InputStreamReader wraps [Link] (which is a byte stream) and converts its
bytes into readable characters - it is the essential link between keyboard byte input and
character-based reading.
Example 11: Reading Characters Until 'q' is Pressed
import [Link].*;
public class ReadConsole {
public static void main(String args[]) throws IOException {
InputStreamReader cin = null;
try {
cin = new InputStreamReader([Link]);
[Link]("Type characters. Press 'q' to quit.");
char c;
do {
c = (char) [Link](); // read one character at a time
[Link](c); // display the character
} while (c != 'q'); // stop when user types 'q'
} finally {
if (cin != null) [Link]();
}
}
}
// SAMPLE OUTPUT:
// Type characters. Press 'q' to quit.
// 1 -> 1
// e -> e
// q -> q (program ends)
12.5.3 BufferedReader (Character Stream)
BufferedReader
Definition 1: BufferedReader ([Link]) is a character stream class that
wraps another Reader and stores characters in an internal buffer, allowing fast, efficient
reading especially of whole lines with readLine().
Definition 2: BufferedReader speeds up input by reading large blocks of characters into
memory at once, then serving them one character or one line at a time from the buffer,
reducing slow disk or network access.
Example 12: Reading File Line by Line with BufferedReader
import [Link].*;
public class ReadLines {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(
new FileReader("c:\\data\\[Link]"));
String line;
while ((line = [Link]()) != null) { // null = end of
file
[Link](line);
}
[Link](); // close to release the file
}
}
// Reads and prints every line from [Link]
Rule
Always call close() after finishing with any stream, reader, or writer. This ensures the file is
properly saved and system resources are released.
Unit 12 - Summary of Key Classes
Class Category Package Main Purpose
InputStream Byte Input [Link] Abstract base - read bytes
OutputStream Byte Output [Link] Abstract base - write bytes
FileInputStream Byte Input [Link] Read bytes from a file
FileOutputStream Byte Output [Link] Write bytes to a file
Scanner Text Input [Link] Read user input easily (int, double, String)
BufferedReader Text Input [Link] Fast line-by-line reading with buffer
DataInputStream Text Input [Link] Read lines from keyboard via readLine()
Reader Char Input [Link] Abstract base - read characters
Writer Char Output [Link] Abstract base - write characters
FileReader Char Input [Link] Read characters from a text file
FileWriter Char Output [Link] Write characters to a text file
InputStreamReader Bridge [Link] Convert byte stream to character stream
BufferedWriter Char Output [Link] Fast buffered character writing
End-of-Unit Practice Activities
Activity 1 - Sum, Average and Difference
Write a Java program that allows the user to input data through the keyboard and calculate the sum,
average and difference of the numbers entered.
Activity 2 - Prime Number Check
Write a Java program that asks the user to enter any number and determines whether the number is a
prime number or not.
Activity 3 - Finding the Youngest
Write a Java program that allows the user to enter the ages of KARENZI, SINGIZWA and MPORE, then
prints the name of the youngest person. Use Scanner class for input.
Activity 4 - File Reading
Write a Java program that reads input from a text file containing: 'Rwanda is a country of one thousand
hills located in East Africa Region' and displays the whole content exactly as it appears.
Activity 5 - Analyze and Find the Output
Study the program below and determine what output it will produce: import [Link]; class
AreaTriangleDemo { public static void main(String args[]) { Scanner scanner = new
Scanner([Link]); [Link]("Enter the width of the Triangle:"); double base =
[Link](); [Link]("Enter the height of the Triangle:"); double height =
[Link](); double area = (base * height) / 2; [Link]("Area of Triangle is: " +
area); } }