DEV Community

Cover image for Java I/O Basics: A Newbie's Guide to Input and Output Streams
Arkadipta kundu
Arkadipta kundu

Posted on

Java I/O Basics: A Newbie's Guide to Input and Output Streams

When I first heard about Java I/O, I thought, “How hard can reading and writing files be?” But as soon as I saw InputStreams, OutputStreams, Readers, Writers, and Serialization, I realized there was a lot more to it than I expected.

If you're like me—just starting to learn about Java file handling and streams—this guide is for you! I'll walk you through what I learned, the confusions I had, and how I finally understood Java I/O in a simple, structured way.

By the end of this guide, you’ll know:
✔️ How Java handles file reading and writing
✔️ The difference between Character Streams & Byte Streams
✔️ How to read & write text files efficiently
✔️ How to work with binary files & serialization

Let's start from the very basics! 🚀

1️⃣ What Are Java I/O Streams? (My First Confusion 🤯)

The first time I saw Java I/O, I noticed the word "stream" everywhere—FileInputStream, FileOutputStream, BufferedReader, PrintWriter...

So I asked myself: What is a stream?
🔹 Understanding Streams

A stream in Java is like a pipeline that moves data from one place to another, such as:

From a file to your program (reading input)

From your program to a file (writing output)
Enter fullscreen mode Exit fullscreen mode

Think of it like water flowing through a pipe! 🌊

2️⃣ Types of Java I/O Streams (The Two Big Categories)

When working with files, Java gives you two types of streams:
Stream Type Used For Read Class Write Class
Character Streams Reading/writing text files FileReader FileWriter
Byte Streams Reading/writing binary files FileInputStream FileOutputStream

📝 Key Takeaway:
`
Use Character Streams for text files (like .txt).

Use Byte Streams for binary files (like images, PDFs).`
Enter fullscreen mode Exit fullscreen mode

At first, I tried to use FileInputStream to read a .txt file, and I got weird numbers instead of words. That’s when I realized: I was using the wrong type of stream! 😅

3️⃣ Writing to a File in Java (My First Success ✅)

The first thing I wanted to try was writing to a file. Here’s the simplest way I found:
🔹 Using FileWriter to Write a Text File:

`import java.io.FileWriter;
import java.io.IOException;

public class FileWriteExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, this is my first file write operation!");

writer.close();
System.out.println("Successfully written to file.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}`

✅ This code creates (or overwrites) output.txt and writes "Hello, this is my first file write operation!" inside it.

When I ran this, I checked my project folder, and boom! There was my file! 🎉

4️⃣ Reading from a File in Java (Fixing My First Mistake 🚨)

After writing to a file, I wanted to read it back. My first mistake was using FileInputStream, which gave me weird numbers instead of text.

Then, I realized that for text files, I should use FileReader!
🔹 Using FileReader to Read a Text File

`import java.io.FileReader;
import java.io.IOException;

public class FileReadExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("output.txt");
int data;
while ((data = reader.read()) != -1) {

System.out.print((char) data);
}
reader.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}`

✅ Reads output.txt character by character and prints it to the console.

5️⃣ Buffered Streams – A Faster Way to Read & Write Files

When working with large text files, I found that FileReader reads one character at a time, which can be slow. That’s where Buffered Streams help!
🔹 Writing Efficiently Using BufferedWriter

`import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriteExample {
public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("buffered_output.txt"));
writer.write("BufferedWriter makes writing faster!");
writer.newLine(); // Adds a new line
writer.write("This is the second line.");
writer.close();
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}`

✅ Writes multiple lines efficiently!

6️⃣ Byte Streams – Handling Binary Files (Like Images & PDFs)

I also learned that text files are not the only thing we deal with. For binary files (like images, videos, PDFs), we use Byte Streams instead of Character Streams.
🔹 Writing Binary Data Using FileOutputStream

`import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamExample {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("binary_output.dat");
fos.write(72); // Writing 'H' ASCII (72)
fos.write(101); // Writing 'e'
fos.close();
System.out.println("Binary file written successfully.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}`

✅ Writes binary data (H and e ASCII values).

7️⃣ Serialization – Saving Java Objects to Files

The coolest thing I learned was that Java can save entire objects to files! This is called Serialization.
🔹 Writing an Object to a File (Serialization)

`import java.io.*;

class Person implements Serializable {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}

public class SerializeExample {
public static void main(String[] args) {
try {
Person p = new Person("John", 30);
FileOutputStream fos = new FileOutputStream("person.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p);
oos.close();
fos.close();
System.out.println("Object serialized successfully.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}`

✅ Saves Person object into person.ser file.

In a nutshell 🥜

✔️ Use FileReader & FileWriter for text files
✔️ Use BufferedReader & BufferedWriter for efficient text reading/writing
✔️ Use FileInputStream & FileOutputStream for binary files
✔️ Use Serialization (ObjectOutputStream) to save Java objects

At first, Java I/O felt complicated, but once I started using it, everything made sense! 🎉

If you’re also learning Java I/O, I’d love to hear your thoughts! Let’s discuss in the comments. 👇🏻🚀

Top comments (0)