Java.lang.String.getBytes() 方法



描述

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

宣告

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

public byte[] getBytes(Charset charset)

引數

charset - 這是用於編碼字串的字元集。

返回值

此方法返回生成的位元組陣列。

異常

示例

以下示例演示了 java.lang.String.getBytes() 方法的使用。

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) {

      try {
         String str1 = "admin";
         System.out.println("string1 = " + str1);
         
         // copy the contents of the String to a byte array
         byte[] arr = str1.getBytes("ASCII");
     
         String str2 = new String(arr);
         
         // print the contents of the byte array
         System.out.println("new string = " + str2);
      } catch(Exception e) {
         System.out.print(e.toString());
      }
   }
}

讓我們編譯並執行以上程式,這將產生以下結果:

string1 = admin
new string = admin
java_lang_string.htm
廣告

© . All rights reserved.