Java String getBytes()方法

Java String getBytes()方法使用平台的默认字符集将此String编码为字节序列,并将结果存储到新的字节数组中。

语法

以下是此方法的语法 -

public byte[] getBytes()

参数

  • N/A

返回值

  • 返回结果为字节数组。

示例

import java.io.*;
public class Test {

    public static void main(String args[]) {
          String Str1 = new String("Welcome to xuhuhu.com");

          try {
             String Str2 = new String( Str1.getBytes( "UTF-8" ));
             System.out.println("Returned Value " + Str2 );
             Str2 = new String (Str1.getBytes( "ISO-8859-1" ));
             System.out.println("Returned Value " + Str2 );
          } catch ( UnsupportedEncodingException e) {
             System.out.println("Unsupported character set");
          }
       }
}

执行上面示例代码,得到以下结果:

Returned Value Welcome to xuhuhu.com
Returned Value Welcome to xuhuhu.com

上一篇: Java String类 下一篇: Java快速入门