Java getBytes() Method

Java String类Java String Class


The getBytes() method has two forms:

  • getBytes(String charsetName):Encodes a string into a sequence of bytes using the specified charset, and stores the result into a new byte array.

  • getBytes(): Encodes a string into a sequence of bytes using the platform's default charset, and stores the result into a new byte array.

Syntax

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

或

public byte[] getBytes()

Parameters

  • charsetName-- The name of a supported charset.

Return Value

Returns a byte array.

Example

import java.io.*; public class Test { public static void main(String args[]) { String Str1 = new String("example"); try{ byte[] Str2 = Str1.getBytes(); System.out.println("Return value:" + Str2 ); Str2 = Str1.getBytes( "UTF-8" ); System.out.println("Return value:" + Str2 ); Str2 = Str1.getBytes( "ISO-8859-1" ); System.out.println("Return value:" + Str2 ); } catch ( UnsupportedEncodingException e){ System.out.println("Unsupported charset"); } } }

The output of the above program is:

返回值:[B@7852e922
返回值:[B@4e25154f
返回值:[B@70dea4e

Java String类Java String Class

Other extensions