Java.lang.String.getBytes() 方法



描述

java.lang.String.getBytes(String charsetName) 方法使用指定的字元集將此字串編碼為一系列位元組,並將結果儲存到一個新的位元組陣列中。

宣告

以下是 java.lang.String.getBytes() 方法的宣告:

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

public byte[] getBytes(String charsetName)

引數

charset − 這是支援的字元集的名稱。

返回值

此方法返回結果位元組陣列。

異常

UnsupportedEncodingException − 如果不支援指定的字元集。

示例

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) throws Exception {
  
      // string with numbers and some special characters    
      String str = "!$0123@";
    
      // byte array with charset
      byte bval[] = str.getBytes("UTF8");
  
      // prints the byte array
      for (int i = 0; i < bval.length; i++) {
         System.out.println(bval[i]);
      }
   }
}

現場演示

33
36
48
49
50
51
64
讓我們編譯並執行以上程式,將產生以下結果 −
列印頁面
廣告