In this section, we will explore the BufferedReader
and BufferedWriter
classes in Java, which are used for reading and writing text from and to character streams efficiently. These classes are part of the java.io
package and provide buffering capabilities to improve the performance of I/O operations.
Key Concepts
BufferedReader
- Purpose: To read text from an input stream efficiently.
- Buffering: It buffers the input to provide efficient reading of characters, arrays, and lines.
- Common Methods:
read()
: Reads a single character.read(char[] cbuf, int off, int len)
: Reads characters into a portion of an array.readLine()
: Reads a line of text.
BufferedWriter
- Purpose: To write text to an output stream efficiently.
- Buffering: It buffers the output to provide efficient writing of characters, arrays, and strings.
- Common Methods:
write(int c)
: Writes a single character.write(char[] cbuf, int off, int len)
: Writes a portion of an array of characters.write(String s, int off, int len)
: Writes a portion of a string.newLine()
: Writes a line separator.flush()
: Flushes the stream.
Practical Examples
Example 1: Reading a File Using BufferedReader
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }
Explanation:
- We create a
BufferedReader
object by wrapping aFileReader
object. - We use a
while
loop to read each line of the file untilreadLine()
returnsnull
. - Each line is printed to the console.
Example 2: Writing to a File Using BufferedWriter
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExample { public static void main(String[] args) { try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) { bw.write("Hello, World!"); bw.newLine(); bw.write("This is a test."); } catch (IOException e) { e.printStackTrace(); } } }
Explanation:
- We create a
BufferedWriter
object by wrapping aFileWriter
object. - We use the
write()
method to write strings to the file. - The
newLine()
method is used to write a line separator. - The
try-with-resources
statement ensures that theBufferedWriter
is closed automatically.
Practical Exercises
Exercise 1: Reading and Writing Files
Task: Write a program that reads from a file named input.txt
and writes its content to a file named output.txt
using BufferedReader
and BufferedWriter
.
Solution:
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileCopyExample { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("input.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) { String line; while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); } } catch (IOException e) { e.printStackTrace(); } } }
Explanation:
- We create a
BufferedReader
to read frominput.txt
. - We create a
BufferedWriter
to write tooutput.txt
. - We read each line from the input file and write it to the output file, adding a new line after each line.
Common Mistakes and Tips
- Forgetting to Close Streams: Always close your streams to free up system resources. Use try-with-resources to handle this automatically.
- Not Handling Exceptions: Always handle
IOException
when performing file I/O operations. - Buffer Size: The default buffer size is usually sufficient, but you can specify a larger buffer size if needed for performance reasons.
Conclusion
In this section, we learned about BufferedReader
and BufferedWriter
, which are essential for efficient reading and writing of text in Java. We covered their key methods, practical examples, and common mistakes. Understanding these classes will help you handle file I/O operations more effectively in your Java applications. In the next section, we will delve into serialization, which allows you to convert objects into a byte stream for storage or transmission.
Java Programming Course
Module 1: Introduction to Java
- Introduction to Java
- Setting Up the Development Environment
- Basic Syntax and Structure
- Variables and Data Types
- Operators
Module 2: Control Flow
Module 3: Object-Oriented Programming
- Introduction to OOP
- Classes and Objects
- Methods
- Constructors
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Module 4: Advanced Object-Oriented Programming
Module 5: Data Structures and Collections
Module 6: Exception Handling
Module 7: File I/O
Module 8: Multithreading and Concurrency
- Introduction to Multithreading
- Creating Threads
- Thread Lifecycle
- Synchronization
- Concurrency Utilities
Module 9: Networking
- Introduction to Networking
- Sockets
- ServerSocket
- DatagramSocket and DatagramPacket
- URL and HttpURLConnection