Metoda Java String getBytes () kóduje řetězec do sekvence bajtů a ukládá jej do bajtového pole.
Syntaxe getBytes()
metody String jsou:
string.getBytes() string.getBytes(Charset charset) string.getBytes(String charsetName)
Zde je řetězec objektem String
třídy.
getBytes()
Metoda vrací bajtové pole.
1. getBytes () bez jakýchkoli parametrů
Pokud nepředáte žádné parametry, getBytes()
zakóduje řetězec pomocí výchozí znakové sady platformy.
Příklad: getBytes () bez jakýchkoli parametrů
import java.util.Arrays; class Main ( public static void main(String() args) ( String str = "Java"; byte() byteArray; // convert the string to a byte array // using platform's default charset byteArray = str.getBytes(); System.out.println(Arrays.toString(byteArray)); ) )
Výstup
(74, 97, 118, 97)
Poznámka:Arrays
Třídu ve výše uvedeném příkladu jsme použili k tisku bajtového pole ve čitelné formě. Nemá to nic společného getBytes(
).
2. getBytes () S parametrem CharSet
CharSet
V Javě jsou k dispozici různé možnosti :
- UTF-8 - osmibitový formát transformace UCS
- UTF-16 - šestnáctibitový formát transformace UCS
- UTF-16BE - šestnáctibitový formát transformace UCS, pořadí bajtů big-endian
- UTF-16LE - Šestnáctibitový formát transformace UCS, pořadí bajtů little-endian
- US-ASCII - sedmbitový ASCII
- ISO-8859-1 - ISO latinská abeceda č. 1
Příklad: getBytes () S parametrem CharSet
import java.util.Arrays; import java.nio.charset.Charset; class Main ( public static void main(String() args) ( String str = "Java"; byte() byteArray; // using UTF-8 for encoding byteArray = str.getBytes(Charset.forName("UTF-8")); System.out.println(Arrays.toString(byteArray)); // using UTF-16 for encoding byteArray = str.getBytes(Charset.forName("UTF-16")); System.out.println(Arrays.toString(byteArray)); ) )
Výstup
(74, 97, 118, 97) (-2, -1, 0, 74, 0, 97, 0, 118, 0, 97)
Poznámka: Ve výše uvedeném programu jsme importovali java.nio.charset.Charset
použití CharSet
. A jsme importovali Arrays
třídu pro tisk bajtového pole ve čitelné formě.
3. getBytes () S řetězcovým parametrem
Můžete také určit typ kódování getBytes()
pomocí řetězců. Když použijete getBytes()
tímto způsobem, musíte zabalit kód dovnitř try… catch block.
Příklad: getBytes () S řetězcovým parametrem
import java.util.Arrays; class Main ( public static void main(String() args) ( String str = "Java"; byte() byteArray; try ( byteArray = str.getBytes("UTF-8"); System.out.println(Arrays.toString(byteArray)); byteArray = str.getBytes("UTF-16"); System.out.println(Arrays.toString(byteArray)); // wrong encoding // throws an exception byteArray = str.getBytes("UTF-34"); System.out.println(Arrays.toString(byteArray)); ) catch (Exception e) ( System.out.println(e + " encoding is wrong"); ) ) )
Výstup
(74, 97, 118, 97) (-2, -1, 0, 74, 0, 97, 0, 118, 0, 97) java.io.UnsupportedEncodingException: kódování UTF-34 je špatné
Poznámka: Importovali jsme java.util.Arrays pro tisk bajtového pole ve čitelné formě. Nemá to nic společného getBytes()
.