Byte Streams
Byte Streams in Java are used to read and write raw binary data (bytes). They are the foundation of Java I/O and are primarily used for non-text data such as images, audio, video, PDFs, and binary files. This is a core Java I/O concept and a common interview topic.
What Are Byte Streams?
- Work with 8-bit bytes
- Used for binary data
- Platform-independent
- Part of java.io package
- Base classes:
- InputStream
- OutputStream
When to Use Byte Streams
- ✔ Images (.jpg, .png)
- ✔ Audio / video files
- ✔ PDF, ZIP, executable files
- ✔ Network and socket data
- ❌ Not ideal for plain text (use character streams)
Byte Stream Class Hierarchy (Important)
Input Side
InputStream
├── FileInputStream
├── BufferedInputStream
├── DataInputStream
└── ObjectInputStream
Output Side
OutputStream
├── FileOutputStream
├── BufferedOutputStream
├── DataOutputStream
└── ObjectOutputStream
InputStream (Base Class)
Used to read bytes.
Key Methods
int read(); // reads one byte
int read(byte[] b); // reads multiple bytes
void close(); // closes stream
✔ Returns -1 when end of stream is reached
OutputStream (Base Class)
Used to write bytes.
Key Methods
void write(int b); // writes one byte
void write(byte[] b); // writes byte array
void flush(); // forces write
void close(); // closes stream
FileInputStream (Reading Binary Data)
FileInputStream fis = new FileInputStream("image.jpg");
int data;
while ((data = fis.read()) != -1) {
System.out.print(data);
}
fis.close();
✔ Reads byte-by-byte
❌ Slow without buffering
FileOutputStream (Writing Binary Data)
FileOutputStream fos = new FileOutputStream("copy.jpg");
fos.write(65); // writes byte
fos.close();
✔ Creates file if not exists
✔ Overwrites by default
Copying a File Using Byte Streams (Common Example)
FileInputStream fis = new FileInputStream("source.jpg");
FileOutputStream fos = new FileOutputStream("dest.jpg");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fis.close();
fos.close();
✔ Efficient
✔ Real-world usage
Buffered Byte Streams (Performance Boost)
BufferedInputStream & BufferedOutputStream
- Use internal buffer
- Reduce disk I/O operations
- Faster than plain streams
BufferedInputStream bis =
new BufferedInputStream(new FileInputStream("a.jpg"));
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream("b.jpg"));
✔ Always preferred for large files
Byte Streams vs Character Streams (Interview Table)
| Aspect | Byte Streams | Character Streams |
|---|---|---|
| Data type | Bytes | Characters |
| File type | Binary | Text |
| Base classes | InputStream / OutputStream | Reader / Writer |
| Encoding | ❌ No | ✔ Yes |
| Example | Image, PDF | Text, CSV |
Common Byte Stream Classes (Must Remember)
- FileInputStream
- FileOutputStream
- BufferedInputStream
- BufferedOutputStream
- DataInputStream
- DataOutputStream
- ObjectInputStream
- ObjectOutputStream
Common Beginner Mistakes
- Using byte streams for text files
- Forgetting to close streams
- Not using buffering
- Reading byte-by-byte unnecessarily
- Ignoring exception handling
Best Practices
- Use buffered streams for performance
- Use try-with-resources for auto-close
- Use byte streams only for binary data
- Prefer NIO (Files.copy) for modern code
try (FileInputStream fis = new FileInputStream("a.jpg");
FileOutputStream fos = new FileOutputStream("b.jpg")) {
// logic
}
Interview-Ready Answers
Short Answer
Byte streams are used to read and write binary data in Java.
Detailed Answer
In Java, byte streams are based on InputStream and OutputStream classes and are used to handle raw binary data such as images, audio, and files. They operate on bytes, are platform-independent, and form the foundation of Java I/O.
Byte Stream Examples (Interview Cheat Sheet)
1. Writing Bytes to a File (FileOutputStream)
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("data.bin");
fos.write(65); // ASCII 'A'
fos.close();
}
}
Key Point
- Writes one byte
- Creates file if not present
2. Writing Multiple Bytes
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("data.bin");
byte[] bytes = {65, 66, 67};
fos.write(bytes);
fos.close();
}
}
Output in file
ABC
3. Reading a File (FileInputStream)
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("data.bin");
int b;
while ((b = fis.read()) != -1) {
System.out.print((char) b);
}
fis.close();
}
}
4. Reading into Byte Array (Efficient)
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("data.bin");
byte[] buffer = new byte[1024];
int length = fis.read(buffer);
System.out.println(new String(buffer, 0, length));
fis.close();
}
}
5. Appending Data to File
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
FileOutputStream fos =
new FileOutputStream("data.bin", true);
fos.write(68); // 'D'
fos.close();
}
}
Key Point
- true → append mode
6. Copying a File (Classic Interview Example)
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("source.bin");
FileOutputStream fos = new FileOutputStream("target.bin");
int b;
while ((b = fis.read()) != -1) {
fos.write(b);
}
fis.close();
fos.close();
}
}
7. Copying File Using Buffer (Better Performance)
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("source.bin");
FileOutputStream fos = new FileOutputStream("target.bin");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fis.close();
fos.close();
}
}
8. BufferedInputStream & BufferedOutputStream
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream("data.bin"));
bos.write("Hello".getBytes());
bos.close();
}
}
Why
- Reduces disk I/O calls
- Faster than plain streams
9. Reading Binary File (Image / PDF)
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("image.png");
System.out.println("File size: " + fis.available());
fis.close();
}
}
Key Point
- Byte streams handle binary data
10. Try-With-Resources (Best Practice)
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
try (FileInputStream fis = new FileInputStream("data.bin")) {
System.out.println(fis.read());
}
}
}
Why
- Auto-closes resources
- Prevents memory leaks
11. Writing String as Bytes
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("text.bin");
fos.write("Java IO".getBytes());
fos.close();
}
}
12. Overwriting File (Default Behavior)
new FileOutputStream("data.bin"); // overwrites existing file
Interview Trap
File content lost if append not enabled
13. Handling FileNotFoundException
import java.io.*;
class Demo {
public static void main(String[] args) {
try {
new FileInputStream("missing.bin");
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
}
14. Difference: Byte Stream vs Character Stream
FileInputStream // binary data
FileReader // text data
15. Reading All Bytes at Once (Java 9+)
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
byte[] data =
new FileInputStream("data.bin").readAllBytes();
System.out.println(new String(data));
}
}
16. Common Interview Trap – Forgetting to Close Stream
FileOutputStream fos = new FileOutputStream("a.bin");
fos.write(65);
// fos.close(); // ❌ resource leak
17. Byte Stream with Command Line Arguments
import java.io.*;
class Demo {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream(args[0]);
FileOutputStream fos = new FileOutputStream(args[1]);
fis.transferTo(fos);
fis.close();
fos.close();
}
}
18. Using transferTo() (Java 9+)
fis.transferTo(fos);
Why
- Cleaner & optimized copying
19. When to Use Byte Streams
- Images
- Videos
- PDFs
- ZIP files
20. Interview Summary – Byte Streams
InputStream / OutputStream
Key Points
- Works with binary data
- Base classes: InputStream, OutputStream
- File versions: FileInputStream, FileOutputStream
- Use buffering for performance
- Close streams properly
Key Takeaway
Byte Streams = Binary Data Handling.
Use them for non-text files, add buffering for performance, and prefer modern NIO APIs in production.