ByteArrayOutputStream reset() method in Java with Examples


The reset() method of ByteArrayOutputStream class in Java resets the count field of the ByteArrayOutputStream to zero, so that all the subsequent writes will overwrite any previous data.

Syntax:

public synchronized void reset()

Parameters: This method does not take any parameters.

Return Value: This method does not return any value.

Examples:

Example 1: Using reset() method to clear the contents of ByteArrayOutputStream

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ResetExample {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write("Hello World".getBytes());
        System.out.println("Before reset(): " + baos.toString());
        baos.reset();
        System.out.println("After reset(): " + baos.toString());
    }
}

Output:

Before reset(): Hello World
After reset():

In the above example, we have created a ByteArrayOutputStream object baos and written a string "Hello World" to it using the write() method. Then we have printed the contents of the baos using the toString() method. After that, we have called the reset() method to clear the contents of the baos. Finally, we have printed the contents of the baos again, which is now empty.

Example 2: Using reset() method to reuse the ByteArrayOutputStream

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ReuseExample {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write("Hello".getBytes());
        System.out.println("Before reset(): " + baos.toString());
        baos.reset();
        baos.write("World".getBytes());
        System.out.println("After reset(): " + baos.toString());
    }
}

Output:

Before reset(): Hello
After reset(): World

In the above example, we have created a ByteArrayOutputStream object baos and written a string "Hello" to it using the write() method. Then we have printed the contents of the baos using the toString() method. After that, we have called the reset() method to clear the contents of the baos. Then we have written a new string "World" to the baos using the write() method. Finally, we have printed the contents of the baos again, which is now "World".

This example shows how we can reuse the same ByteArrayOutputStream object by resetting it instead of creating a new object every time.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.