Junior
What is the purpose of using buffered streams?
sobes.tech AI
Answer from AI
Buffered streams use an internal buffer to minimize direct interaction with the underlying I/O resource (file, network). Instead of sending or reading data byte by byte or character by character, data is accumulated in the buffer and then read or written in larger blocks. This significantly reduces the number of accesses to slow I/O operations, thereby increasing performance.
Examples of buffered streams:
BufferedInputStreamBufferedOutputStreamBufferedReaderBufferedWriter
// Example of using BufferedReader
try (BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
The idea is to optimize: instead of many small I/O operations, fewer larger ones are performed, reducing overhead.