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


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


描述

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

聲明

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

public byte[] getBytes()

參數

NA

返回值

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

異常

NA

示例

下麵的例子展示了 java.lang.String.getBytes() 方法的用法。

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) {

      String str1 = "tutorials point";
   
      // copy contents of str1 to a byte array.
      byte[] val = str1.getBytes();

      // create string str1 using the contents of the byte array
      String str2 = new String(val);

      // prints the byte array.
      System.out.println("String '" + str2 + "' is equal to str1");
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果——

String 'tutorials point' is equal to str1

相關用法


注:本文由純淨天空篩選整理自 Java.lang.String.getBytes() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。