Skip to main content
Advertisement

Java I/O (Input/Output) Overview

In Java, Input/Output (I/O) refers to the process of transferring data between the computer's internal memory and external devices such as the keyboard, monitor, files, and network. Java's java.io package provides various classes that handle this data I/O in a consistent manner.

1. Node Streams

The core of Java I/O is the Node Stream(Base Stream), which perfectly connects directly to the source or destination of external data (like files or networks) to read or write data. Depending on the type of data being handled, they are divided into two main categories:

Byte-based Streams

These transfer data in units of 1 byte. They can transmit all types of data, including images, videos, audio, and text. They use InputStream and OutputStream as their top-level abstract classes.

  • FileInputStream / FileOutputStream (Files)
  • ByteArrayInputStream / ByteArrayOutputStream (Memory arrays)

Character-based Streams

Because a Java char is 2 bytes, handling text data utilizing a 1-byte based stream can cause languages with multibyte characters (like Korean, Chinese, Japanese) to become corrupted. Thus, these streams were created uniquely to handle text data (characters). They use Reader and Writer as their top-level abstract classes.

  • FileReader / FileWriter (Text files)
  • StringReader / StringWriter (Strings in memory)

2. File I/O Example

This is the most standard logic for reading and writing files. System resources must absolutely be returned via close() after using them. Using the try-with-resources syntax introduced in Java 7 automatically closes them for you.

import java.io.*;

public class FileIOExample {
public static void main(String[] args) {
// Writing a string to a file
try (FileWriter fw = new FileWriter("test.txt")) {
fw.write("Hello, World!\nWelcome to Java.");
} catch (IOException e) {
e.printStackTrace();
}

// Reading a string from a file
try (FileReader fr = new FileReader("test.txt")) {
int data;
// read() returns -1 when the end of the file is reached
while ((data = fr.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Streams flow strictly in one direction (unidirectionally). Therefore, you must create a stream purely for Input and another completely separate stream for Output.

Advertisement