Skip to main content

Java Exception Handling MCQ Test

  Loading…

Buffered Streams

Buffered Streams in Java:

Buffered streams are used to improve the performance of input/output operations by reducing the number of system calls. They achieve this by using an internal buffer to read from or write to the underlying input/output stream in larger chunks, rather than one byte or character at a time.


Buffered Input Stream Classes:

- `BufferedInputStream`: Provides buffering for input bytes, allowing the reading of data from an underlying input stream.

- `BufferedReader`: Reads text from a character-input stream, buffering characters to provide efficient reading of characters, arrays, and lines.


Buffered Output Stream Classes:

- `BufferedOutputStream`: Provides buffering for output bytes, allowing the writing of data to an underlying output stream.

- `BufferedWriter`: Writes text to a character-output stream, buffering characters to provide efficient writing of characters, arrays, and lines.


Example: Reading from a File using BufferedReader:


import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;


public class BufferedStreamExample {

    public static void main(String[] args) {

        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {

            String line;

            while ((line = reader.readLine()) != null) {

                System.out.println(line);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}



Explanation:

- In this example, we use `BufferedReader` to read text from a file ("example.txt").

- We wrap a `FileReader` with a `BufferedReader` to buffer the input and improve reading performance.

- The `readLine()` method of `BufferedReader` reads a line of text from the input stream. If the end of the stream is reached, it returns `null`.

- We use a `try-with-resources` statement to automatically close the `BufferedReader` when the block ends, ensuring proper resource management.


Benefits of Buffered Streams:

- Reduced number of system calls: Buffered streams reduce the number of system calls by reading or writing data in larger chunks.

- Improved performance: Buffered streams typically provide faster read/write operations compared to their unbuffered counterparts.

- Convenient API: Buffered streams offer convenient methods for reading and writing data, such as `readLine()` in `BufferedReader` for reading lines of text.


------------------------


Here's an example demonstrating the usage of `BufferedWriter` in Java:


import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;


public class BufferedWriterExample {

    public static void main(String[] args) {

        String filename = "output.txt";


        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {

            writer.write("Hello, World!");

            writer.newLine(); // Write a newline character


            // Writing multiple lines

            writer.write("This is an example of BufferedWriter.");

            writer.newLine();

            writer.write("It provides efficient writing of characters, arrays, and lines.");


            System.out.println("Data has been written to " + filename);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}


Explanation:

- We create a `BufferedWriter` object and wrap it around a `FileWriter`, specifying the file name ("output.txt") to write to.

- Using the `write()` method, we write a string to the file. The `newLine()` method is called to insert a newline character after each line.

- Multiple lines of text are written to the file using separate `write()` calls.

- The `try-with-resources` statement is used to automatically close the `BufferedWriter` when the block ends, ensuring proper resource management.

- If any `IOException` occurs during the writing process, it is caught and the stack trace is printed.


This example demonstrates how `BufferedWriter` can efficiently write text data to a file by buffering the output, which can lead to improved performance compared to writing directly to the file.

----------------


Here's a program that reads input from the user using `BufferedReader` and writes it to a file using `BufferedWriter`:


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStreamReader;


public class BufferedIOExample {

    public static void main(String[] args) {

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

             BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {


            // Read input from the user

            System.out.println("Enter text (type 'exit' to quit):");

            String line;

            while (!(line = reader.readLine()).equalsIgnoreCase("exit")) {

                // Write input to a file

                writer.write(line);

                writer.newLine(); // Write a newline character

            }


            System.out.println("Data has been written to output.txt");

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}



Explanation:

- We create a `BufferedReader` object `reader` to read input from the user via `System.in`.

- We create a `BufferedWriter` object `writer` to write data to a file named "output.txt".

- Inside the `while` loop, we continuously read lines of input from the user using `reader.readLine()`.

- If the user types "exit", the loop terminates.

- For each line read from the user, we write it to the file using `writer.write(line)` and add a newline character using `writer.newLine()`.

- The `try-with-resources` statement ensures that both `reader` and `writer` are properly closed after use.

- If any `IOException` occurs during the process, it is caught and the stack trace is printed.



In summary, buffered streams in Java improve I/O performance by reducing system calls and providing efficient buffering of data. They are commonly used in applications where I/O performance is critical, such as reading/writing large files or network communication.

Comments

Popular posts from this blog

Passing and Returning Objects in Java Methods

Passing and Returning Objects in Java Methods In Java, objects can be passed as parameters to methods and returned from methods just like other primitive data types. This allows for flexibility and the manipulation of object state within methods. Let's explore how passing and returning objects work in Java. Passing Objects as Parameters When you pass an object as a parameter to a method, you are essentially passing a reference to that object. This means that changes made to the object inside the method will affect the original object outside the method.  Example: class Car {     String model;     Car(String model) {         this.model = model;     } } public class CarProcessor {     // Method to modify the Car object     static void modifyCar(Car car, String newModel) {         car.model = newModel;     }     public static void main(String[] args) {       ...

Chained Exceptions

 Chained exceptions, also known as nested exceptions, allow you to associate one exception with another. This feature is useful when you want to provide more context or information about the cause of an exception. In Java, you can chain exceptions using constructors that take a `Throwable` (or its subclasses) as an argument. Syntax: try {     // Code that may throw an exception } catch (ExceptionType1 e1) {     throw new ExceptionType2("Additional information", e1); } Explanation: - Inside a `catch` block, you can create a new exception object and pass the original exception (`e1`) as the cause. - The chained exception (`ExceptionType2`) includes a message and the original exception (`e1`) as its cause. - This technique allows you to preserve the original exception's stack trace and context while providing additional information about the higher-level exception. - Chained exceptions can be caught and processed at higher levels of the call stack, allowing for bet...