菜鸟教程 -- 学的不仅是技术,更是梦想!

Java 教程
(追記) (追記ここまで)

Java getBytes() 方法

Java String类Java String类


getBytes() 方法有两种形式:

  • getBytes(String charsetName): 使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

  • getBytes(): 使用平台的默认字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

语法

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
或
public byte[] getBytes()

参数

  • charsetName -- 支持的字符集名称。

返回值

返回 byte 数组。

实例

importjava.io.*; publicclassTest{publicstaticvoidmain(Stringargs[]){StringStr1 = newString("runoob"); try{byte[]Str2 = Str1.getBytes(); System.out.println("返回值:" + Str2); Str2 = Str1.getBytes("UTF-8"); System.out.println("返回值:" + Str2); Str2 = Str1.getBytes("ISO-8859-1"); System.out.println("返回值:" + Str2); }catch(UnsupportedEncodingExceptione){System.out.println("不支持的字符集"); }}}

以上程序执行结果为:

返回值:[B@7852e922
返回值:[B@4e25154f
返回值:[B@70dea4e

Java String类Java String类

AI 思考中...

1 篇笔记 写笔记

  1. #0

    Make a fortune

    540***[email protected]

    70

    可用如下方法查看字符串用 getBytes() 方法处理后返回的 byte[] 数组中的内容:

    class Main {
     public static void main(String[] args) {
     String str = "make a fortune";
     byte[] byt = str.getBytes();
     for (byte b : byt) {
     System.out.println(b);
     }
     }
    }

    以上程序运行结果为:

    109
    97
    107
    101
    32
    97
    32
    102
    111
    114
    116
    117
    110
    101

    可见 byte[] 数组中存放的是字符串响应位置对应的字母的哈希值,如字符串中的字母 a 对应 byte[] 数组中的 97 。

    另外:返回的 byte[] 数组的长度,与原字符串的长度相等。

    Make a fortune

    540***[email protected]

    8年前 (2018年04月28日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /