ByteArrayOutputStream toString(String) in Java

toString(String): This method is available in the java.io.ByteArrayOutputStream class of Java.

Syntax:

String java.io.ByteArrayOutputStream.toString(String charsetName) throws UnsupportedEncodingException

This method takes one argument. This method converts the buffer's contents into a string by decoding the bytes using the named charset.

Parameters: One parameter is required for this method.

charsetName: the name of a supported charset.

Returns: String decoded from the buffer's contents.

Throws:

UnsupportedEncodingException - If the named charset is not supported.

Approach 1: When no exception

Java

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

public class ByteArrayOutputStreamtoString2 {
    public static void main(String[] args) throws IOException {

        ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream();

        byte[] buffer = { 'H', 'E', 'L', 'L', 'O' };
        byteArrayOutputStream.write(buffer);
        System.out.println(
byteArrayOutputStream.toString("UTF-8"));
        byteArrayOutputStream.close();
    }
}

Output:

HELLO


Approach 2: UnsupportedEncodingException 

Java

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

public class ByteArrayOutputStreamtoString2 {
    public static void main(String[] args) throws IOException {

        ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream();

        byte[] buffer = { 'H', 'E', 'L', 'L', 'O' };
        byteArrayOutputStream.write(buffer);
        System.out.println(
byteArrayOutputStream.toString("ABC"));
        byteArrayOutputStream.close();
    }
}

Output:

Exception in thread "main" java.io.UnsupportedEncodingException: ABC at java.base/java.lang.StringCoding.decode(StringCoding.java:249) at java.base/java.lang.String.<init>(String.java:485) at java.base/java.io.ByteArrayOutputStream.toString(ByteArrayOutputStream.java:252)


No comments:

Post a Comment