java中的getbytes()函数用于将字符串转换为字节序列并返回字节数组。此函数可以通过两种方式实现。本文讨论了这两种方式。
- 语法1-public byte[] getBytes():此函数不带参数,并使用默认字符集将字符串编码为字节。
// Java code to demonstrate the working of // getByte() public class GetByte { public static void main(String args[]) { // Initializing String String gfg = "ASTHA GFG"; // Displaying string values before // conversion System.out.println("The String before conversion is : "); System.out.println(gfg); // converting the string into byte // using getBytes ( converts into ASCII values ) byte[] b = gfg.getBytes(); // Displaying converted string after conversion System.out.println("The String after conversion is : "); for (int i = 0; i < b.length; i++) { System.out.print(b[i]); } } }
输出:
The String before conversion is : ASTHA GFG The String after conversion is : 658384726532717071
- 语法2:public byte [] getBytes(Charset charset):此实现接受字符集,根据字符集必须在转换为字节时对其进行编码。定义了许多字符集,下面进行讨论。
- US-ASCII:Seven-bit ASCII,也称为ISO646-US,也称为Unicode字符集的基本拉丁语块
- ISO-8859-1:ISO拉丁字母1号,又名ISO-LATIN-1
- UTF-8:Eight-bit UCS转换格式
- UTF-16BE:十六位UCS转换格式,大端字节顺序
- UTF-16LE:十六位UCS转换格式,低位字节序
- UTF-16:十六位UCS转换格式,由可选字节顺序标记标识的字节顺序。
// Java code to demonstrate the working of // getByte() using different character sets import java.io.*; public class GetBytecharset { public static void main(String args[]) { // Initializing String String gfg = new String("ASTHA GFG"); // Displaying string values before // conversion System.out.println("The String before conversion is : "); System.out.println(gfg); try { // converting the string into byte // using getBytes ( converts into UTF-16 values ) byte[] b = gfg.getBytes("UTF-16"); // Displaying converted string after conversion // into UTF-16 System.out.println("The String after conversion into UTF-16 is : "); for (int i = 0; i < b.length; i++) { System.out.print(b[i]); } System.out.print("\n"); // converting the string into byte // using getBytes ( converts into UTF-16BE values ) byte[] c = gfg.getBytes("UTF-16BE"); // Displaying converted string after conversion // into UTF-16BE System.out.println("The String after conversion into UTF-16BE is : "); for (int i = 0; i < c.length; i++) { System.out.print(c[i]); } } catch (UnsupportedEncodingException g) { System.out.println("Unsupported character set" + g); } } }
输出:
The String before conversion is : ASTHA GFG The String after conversion into UTF-16 is : -2-1065083084072065032071070071 The String after conversion into UTF-16BE is : 065083084072065032071070071
相关用法
- Java Java.util.Collections.disjoint()用法及代码示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代码示例
- Java Java lang.Long.byteValue()用法及代码示例
- Java Java lang.Long.highestOneBit()用法及代码示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代码示例
注:本文由纯净天空筛选整理自 Java.lang.String.getByte() in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。