Java getBytes() Method
The getBytes() method has two forms:
-
getBytes(String charsetName): Encodes the string into a byte sequence using the specified charset and stores the result in a new byte array.
-
getBytes(): Encodes the string into a byte sequence using the platform's default charset and stores the result in a new byte array.
Syntax
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
或
public byte[] getBytes()
Parameters
-
charsetName -- The name of a supported charset.
Return Value
Returns the byte array.
Example
import
java
.
io
.*;
public
class
Test
{
public
static
void
main
(
String
args
[
]
)
{
String
Str1
=
new
String
(
"
runoob
"
)
;
try
{
byte
[
]
Str2
=
Str1
.
getBytes
(
)
;
System
.
out
.
println
(
"
Return Value:
"
Str2
)
;
Str2
=
Str1
.
getBytes
(
"
UTF-8
"
)
;
System
.
out
.
println
(
"
Return Value:
"
Str2
)
;
Str2
=
Str1
.
getBytes
(
"
ISO-8859-1
"
)
;
System
.
out
.
println
(
"
Return Value:
"
Str2
)
;
}
catch
(
UnsupportedEncodingException
e
)
{
System
.
out
.
println
(
"
Unsupported charset
"
)
;
}
}
}
The execution result of the above program is:
返回值:[B@7852e922
返回值:[B@4e25154f
返回值:[B@70dea4e
Java String class