Using I/O in Java
Understanding Input/Output Streams with Examples
Introduction to Java I/O
Java I/O (Input/Output) processes input and produces output.
Involves reading data from a source and writing data to a destination.
Streams
• Java programs perform I/O through streams.
• A stream is an abstraction that either produces or consumes information.
• A stream is linked to a physical device by the Java I/O system.
• Thus, the same I/O classes and methods can be applied to any device.
• This means that an input stream can abstract many kinds of input: from a disk file, a
keyboard, or a network socket.
• Likewise, an output stream may refer to the console, a disk file, or a network
connection.
Streams
• Streams are a clean way to deal with input/output without having every part
of your code understand the difference between a keyboard and a network.
• Java implements streams within class hierarchies defined in the java.io
package
2 types of Streams in Java
Two types of Streams:
• Byte Streams (for binary data) - Byte streams provide a convenient means
for handling input and output of bytes.
• Character Streams (for text data)- provide a convenient means for handling
input and output of characters. They use Unicode and, therefore, can be
internationalized.
The Byte Stream Classes
Stream: Sequence of data.
I/O Classes: Found in the java.io package.
Two Abstract classes with many concrete subclasses
• Input Stream: Reads data from a source.
• Output Stream: Writes data to a destination.
The two most important functions/methods inside the Input Stream and the Output
Stream are:
• read( ) and write( ),
Using Byte Streams
• Used to read/write binary data.
• Classes:
• FileInputStream
• FileOutputStream
Byte Streams
Used for handling binary data (e.g., images, videos).
• Examples of Byte Streams: FileInputStream, FileOutputStream
FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); }
in.close();
out.close();
Reading Using Byte Stream
• import java.io.*;
• public class ByteReadExample {
• public static void main(String[] args) throws IOException {
• FileInputStream fis = new FileInputStream("data.txt");
• int i;
• while ((i = fis.read()) != -1) {
• System.out.print((char) i); }
• fis.close(); }}
Writing Using Byte Stream
• import java.io.*;
• public class ByteWriteExample {
• public static void main(String[] args) throws IOException {
• FileOutputStream fos = new FileOutputStream("data.txt");
• String str = "Hello Byte Stream!";
• fos.write(str.getBytes());
• fos.close(); }}
Byte Streams
(Reading and Writing Binary Data)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamExample {
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("example.txt")) {
String data = "Hello, Byte Streams!";
fos.write(data.getBytes()); // Writing bytes to a file }
catch (IOException e) {
e.printStackTrace(); }
try (FileInputStream fis = new FileInputStream("example.txt")) {
int i; while ((i = fis.read()) != -1) {
System.out.print((char) i); // Reading bytes from a file } }
catch (IOException e) { e.printStackTrace(); } } }
Automatically Closing a File
(Try-with-resources)
• import java.io.*;
• public class AutoCloseExample {
• public static void main(String[] args) {
• try (FileOutputStream fos = new FileOutputStream("auto.txt")) {
• String msg = "Auto-close with try!";
• fos.write(msg.getBytes());
• } catch (IOException e) {
• e.printStackTrace(); } }}
Character streams
• Character streams are defined by using two class hierarchies.
• At the top are two abstract classes, Reader and Writer.
• These abstract classes handle Unicode character streams.
• Java has several concrete subclasses of each of these.
System class
• All Java programs automatically import the java.lang package.
• This package defines a class called System, which encapsulates several
aspects of the run-time environment.
• System also contains three predefined stream variables: in, out, and err.
These fields are declared as public, static, and final within System.
• This means that they can be used by any other part of your program and
without reference to a specific System object.
System class
• System.out refers to the standard output stream. By default, this is the
console.
• System.in refers to standard input, which is the keyboard by default.
• System.err refers to the standard error stream
Reading Characters
• import java.io.*;
• class BRRead {
• public static void main(String args[]) throws IOException {
• char c;
• BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
• System.out.println("Enter characters, 'q' to quit."); // read characters
• do {
• c = (char) br.read();
• System.out.println(c); } while(c != 'q'); } }
• BufferedReader supports a buffered input stream. Its most commonly used constructor is
shown here:
BufferedReader(Reader inputReader)
• Here, inputReader is the stream that is linked to the instance of BufferedReader that is
being created.
• Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which
converts bytes to characters.
• To obtain an InputStreamReader object that is linked to System.in, use the following
constructor:
InputStreamReader(InputStream inputStream).
• As System.in refers to an object of type InputStream, it can be used for an inputStream.
Putting it all together, the following line of code creates a BufferedReader that is connected
to the keyboard:
• BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
Reading Strings
• import java.io.*;
• class BRReadLines {
• public static void main(String args[]) throws IOException { // create a BufferedReader using System.in
• BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
• String str;
• System.out.println("Enter lines of text.");
• System.out.println("Enter 'stop' to quit.");
• do {
• str = br.readLine(); // To read a string from the keyboard, readLine( ) is a member of the BufferedReader class.
• } while(!str.equals("stop")); } }
Using Character-Based Streams
Used for text data.
Classes:
• FileReader
• FileWriter
Character-Based Streams
FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt");
int c; while ((c = reader.read()) != -1) {
writer.write(c); }
reader.close();
writer.close();
File I/O Using FileWriter
• import java.io.*;
• public class CharWriteExample {
• public static void main(String[] args) throws IOException {
• FileWriter fw = new FileWriter("text.txt");
• fw.write("Writing with FileWriter");
• fw.close(); }}
File I/O Using FileReader
• import java.io.*;
• public class CharReadExample {
• public static void main(String[] args) throws IOException {
• FileReader fr = new FileReader("text.txt");
• int i;
• while ((i = fr.read()) != -1) {
• System.out.print((char) i); }
• fr.close(); }}
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharacterStreamExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("example.txt")) {
writer.write("Hello, Character Streams!"); // Writing characters to a file
}
catch (IOException e) { e.printStackTrace(); }
try (FileReader reader = new FileReader("example.txt")) {
int i;
while ((i = reader.read()) != -1) {
System.out.print((char) i); // Reading characters from a file } }
catch (IOException e) { e.printStackTrace(); } } }
Summary
• Use Byte Streams for raw binary data.
• Use Character Streams for text data.
• Always handle exceptions and close streams.
• Use try-with-resources for auto-closing.