Java I/O (Input/Output) is a core concept for every Java developer. This guide covers file handling, streams, readers, writers, and practical code examples to help you master Java I/O for real-world applications.
📋 Table of Contents
🔰 Introduction to Java I/O
Java I/O provides APIs to read and write data (files, network, console). It is built around streams for efficient data transfer.
📁 File Handling Basics
- File Class: Used to represent file and directory pathnames.
- Common Operations: Create, delete, rename, check existence, get info.
// Create a file
File file = new File("example.txt");
file.createNewFile();
// Check if file exists
if (file.exists()) {
System.out.println("File exists");
}
🌊 Streams in Java
Streams are used to read/write data in Java. Two main types:
- Byte Streams: Handle raw binary data (InputStream, OutputStream).
- Character Streams: Handle text data (Reader, Writer).
// Write bytes to a file
FileOutputStream fos = new FileOutputStream("output.txt");
fos.write("Hello World".getBytes());
fos.close();
// Read bytes from a file
FileInputStream fis = new FileInputStream("output.txt");
int ch;
while ((ch = fis.read()) != -1) {
System.out.print((char) ch);
}
fis.close();
📝 Readers & Writers
Readers and Writers are for character data. They simplify text file operations.
// Write text to a file
FileWriter fw = new FileWriter("text.txt");
fw.write("Java I/O is powerful!");
fw.close();
// Read text from a file
FileReader fr = new FileReader("text.txt");
int c;
while ((c = fr.read()) != -1) {
System.out.print((char) c);
}
fr.close();
💡 Practical Examples
- Buffered Streams: Improve performance by reducing disk access.
- Try-with-resources: Auto-close streams to prevent resource leaks.
// BufferedReader example
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
✅ Best Practices
- Always close streams (use try-with-resources)
- Use buffering for large files
- Handle exceptions properly
- Prefer Readers/Writers for text, Streams for binary
❓ FAQ
- Q: What is the difference between FileInputStream and FileReader?
A: FileInputStream is for binary data, FileReader is for character/text data. - Q: How to avoid resource leaks?
A: Use try-with-resources to auto-close streams. - Q: Can Java I/O handle large files?
A: Yes, use buffering and process files in chunks.
🎯 Ready to master Java I/O?
Join our Java Full Stack Developer course for hands-on training and real-world projects.
Explore Our Courses
Join our Java Full Stack Developer course for hands-on training and real-world projects.
Explore Our Courses