Java ByteArrayOutputStream .toString (String charsetName)

Syntax

ByteArrayOutputStream.toString(String charsetName) has the following syntax.

public String toString(String charsetName)  throws UnsupportedEncodingException

Example

In the following code shows how to use ByteArrayOutputStream.toString(String charsetName) method.


/*from  w  w  w .j av  a  2 s  . c  o  m*/


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

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

    byte[] bs = { 65, 66, 67, 68, 69 };

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    baos.write(bs);

    // converts buffers content using Cp1047 character set
    String str = baos.toString("Cp1047");
    System.out.println(str);

    // converts buffers contents using UTF-8 character set
    str = baos.toString("UTF-8");
    System.out.println(str);

  }
}

The code above generates the following result.