當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.lang.String.getBytes()用法及代碼示例


描述

這個java.lang.String.getBytes(Charset charset) 方法使用給定的字符集將此字符串編碼為字節序列,並將結果存儲到新的字節數組中。

聲明

以下是聲明java.lang.String.getBytes()方法

public byte[] getBytes(Charset charset)

參數

charset─ 這是用於對字符串進行編碼的字符集。

返回值

此方法返回結果字節數組。

異常

NA

示例

下麵的例子展示了 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.getBytes() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。