Today, I am going to beak over 1 of the mutual tasks for programmers, converting a String to a byte array. You demand to make that for multiple reasons e.g. for saving content to a file, sending over a network or mayhap around other reason. Suppose you lot receive got a String "abcd" as well as you lot desire to convert it into a byte array, how volition you lot make that inward a Java program? Remember, String is made of the char array, thus it involves grapheme to byte conversion, which is dependent area to character encoding intricacies. Thankfully, Java provides a convenient getBytes() method to convert String to byte array inward Java, simply unfortunately, many developers don't travel it correctly. Almost 70% of the code I receive got reviewed uses getBytes() without grapheme encoding, leaving it on the conduct chances that platform's default grapheme encoding volition last same every bit of the source String.
The right way to travel getBytes() should e'er last amongst explicit grapheme encoding, every bit shown inward this article. Java fifty-fifty comes amongst around touchstone prepare of grapheme encoding which is supported out-of-box yesteryear StandardCharset class, nosotros volition review them every bit well.
It's every bit good a skillful practise is to travel the pre-defined contestants for specifying grapheme encoding inward your code instead of using a costless text or String to avoid typos as well as other featherbrained mistakes.
In past, I receive got shown you lot how to convert a byte array to String inward Java as well as inward this article, I volition demonstrate you lot 3 mutual ways to convert a String to byte array inward Java, let's kickoff amongst the most pop one.
This is the most mutual way to convert a String into a byte array, it plant most of the fourth dimension simply it's error-prone as well as tin make an erroneous termination if platform's grapheme encoding doesn't stand upward for amongst expected encoding.
Here is an instance of converting String to byte[] inward Java :
Remark :
1) Platform's default encoding is used for converting a grapheme to bytes if you lot don't specify whatever grapheme encoding.
2) You tin come across platform's default grapheme encoding yesteryear using System.getProperty("file.encoding");, this render the default grapheme encoding of the machine your JVM is running. You tin see Java Fundamentals: The Core Platform for to a greater extent than details on this topic.
3) Beware, your code may piece of job inward 1 surroundings e.g. QA simply non piece of job inward production because of dissimilar default grapheme encoding. That's why you lot should non rely on default grapheme encoding.
4) length of byte array may non last same every bit the length of String, it depends upon grapheme encoding. Some grapheme encoding is multi-byte simply usually, accept 1 byte to encode ASCII characters.
Remark :
1) It's meliorate than the previous approach simply throws a checked exception java.io.UnsupportedEncodingException, if grapheme encoding String has a typo or specifies as well as grapheme encoding non supported yesteryear Java.
2) The returned byte array is on specified grapheme encoding
3) You tin come across that length of the byte array is not same every bit a seat out of characters inward String every bit was the instance inward the previous instance because UTF-16 encoding takes at-least 2 bytes to encode a character.
Influenza A virus subtype H5N1 skillful matter nigh this approach is that it doesn't throw checked java.io.UnsupportedEncodingException, simply unfortunately this degree is alone available from JDK seven onward thus it mightiness non last an pick for several Java application running on Java half dozen as well as lower version.
Remarks :
1) This is the best way to convert String to a byte array inward Java.
2) This doesn't throw java.io.UnsupportedEncodingException exception, which agency no boilerplate code for treatment this checked exception.
3) Though, you lot must choke on inward in heed that StandarhardCasets degree is alone available from Java seven onward. You tin come across Core Java for the Impatient for to a greater extent than such details, which every bit good covers Java SE 8.
That's all nigh how to convert a String to byte array inward Java. Remember the size of byte array tin last to a greater extent than than the length of String because it's non necessary that 1 byte is used to encode 1 character, it all depends on grapheme encoding. For example, UTF-8 is a multi-byte grapheme encoding system as well as uses betwixt 1 to four bytes per character. In general, characters of the quondam ASCII attain takes 1 bytes simply characters from the quondam ISO-8859 attain beyond ASCII takes 2 bytes.
Other articles you may like
The Java Fundamentals: Java linguistic communication yesteryear Jim Wilson
How to supervene upon characters as well as substring inward given String?
How String inward switch instance plant inward Java?
What is the divergence inward String puddle betwixt Java half dozen as well as 7?
The right way to travel getBytes() should e'er last amongst explicit grapheme encoding, every bit shown inward this article. Java fifty-fifty comes amongst around touchstone prepare of grapheme encoding which is supported out-of-box yesteryear StandardCharset class, nosotros volition review them every bit well.
It's every bit good a skillful practise is to travel the pre-defined contestants for specifying grapheme encoding inward your code instead of using a costless text or String to avoid typos as well as other featherbrained mistakes.
In past, I receive got shown you lot how to convert a byte array to String inward Java as well as inward this article, I volition demonstrate you lot 3 mutual ways to convert a String to byte array inward Java, let's kickoff amongst the most pop one.
String to byte array using getBytes()
This is the most mutual way to convert a String into a byte array, it plant most of the fourth dimension simply it's error-prone as well as tin make an erroneous termination if platform's grapheme encoding doesn't stand upward for amongst expected encoding.Here is an instance of converting String to byte[] inward Java :
// converts String to bytes using platform's default grapheme encoding, // inward Eclipse it's Cp1252 // inward Linux it could last something else byte[] ascii = "abcdefgh".getBytes(); System.out.println("platform's default grapheme encoding : " + System.getProperty("file.encoding")); System.out.println("length of byte array inward default encoding : " + ascii.length); System.out.println("contents of byte array inward default encoding: " + Arrays.toString(ascii)); Output : platform's default grapheme encoding : Cp1252 length of byte array inward default encoding : 8 contents of byte array inward default encoding: [97, 98, 99, 100, 101, 102, 103, 104]
Remark :
1) Platform's default encoding is used for converting a grapheme to bytes if you lot don't specify whatever grapheme encoding.
2) You tin come across platform's default grapheme encoding yesteryear using System.getProperty("file.encoding");, this render the default grapheme encoding of the machine your JVM is running. You tin see Java Fundamentals: The Core Platform for to a greater extent than details on this topic.
3) Beware, your code may piece of job inward 1 surroundings e.g. QA simply non piece of job inward production because of dissimilar default grapheme encoding. That's why you lot should non rely on default grapheme encoding.
4) length of byte array may non last same every bit the length of String, it depends upon grapheme encoding. Some grapheme encoding is multi-byte simply usually, accept 1 byte to encode ASCII characters.
String to byte array using getBytes("encoding)
Here is around other way to convert a String to a byte array simply this fourth dimension yesteryear specifying the proper encoding to travel out whatever gauge or platform default aside.// convert String to bytes of specified grapheme encoding but // every bit good throw checked UnsupportedEncodingException, which pollutes the code try { byte[] utf16 = "abcdefgh".getBytes("UTF-16"); System.out.println("length of byte array inward UTF-16 charater encoding : " + utf16.length); System.out.println("contents of byte array inward UTF-16 encoding: " + Arrays.toString(utf16)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Output : length of byte array in UTF-16 charater encoding : eighteen contents of byte array in UTF-16 encoding: [-2, -1, 0, 97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102, 0, 103, 0, 104]
Remark :
1) It's meliorate than the previous approach simply throws a checked exception java.io.UnsupportedEncodingException, if grapheme encoding String has a typo or specifies as well as grapheme encoding non supported yesteryear Java.
2) The returned byte array is on specified grapheme encoding
3) You tin come across that length of the byte array is not same every bit a seat out of characters inward String every bit was the instance inward the previous instance because UTF-16 encoding takes at-least 2 bytes to encode a character.
String to byte array using getBytes(Charset)
This is 3rd simply in all probability the best way to convert to String to byte[] inward Java. In this example, I receive got used java.nio.StandardCharsets to specify grapheme encoding. This degree contains around of the widely used grapheme encoding constants e.g. UTF-8, UTF-16 etc.Influenza A virus subtype H5N1 skillful matter nigh this approach is that it doesn't throw checked java.io.UnsupportedEncodingException, simply unfortunately this degree is alone available from JDK seven onward thus it mightiness non last an pick for several Java application running on Java half dozen as well as lower version.
// render bytes inward UTF-8 grapheme encoding // pros - no demand to grip UnsupportedEncodingException // pros - bytes inward specified encoding scheme byte[] utf8 = "abcdefgh".getBytes(StandardCharsets.UTF_8); System.out.println("length of byte array inward UTF-8 : " + utf8.length); System.out.println("contents of byte array inward UTF-8: " + Arrays.toString(utf8)); Output : length of byte array in UTF-8 : 8 contents of byte array in UTF-8: [97, 98, 99, 100, 101, 102, 103, 104]
Remarks :
1) This is the best way to convert String to a byte array inward Java.
2) This doesn't throw java.io.UnsupportedEncodingException exception, which agency no boilerplate code for treatment this checked exception.
3) Though, you lot must choke on inward in heed that StandarhardCasets degree is alone available from Java seven onward. You tin come across Core Java for the Impatient for to a greater extent than such details, which every bit good covers Java SE 8.
That's all nigh how to convert a String to byte array inward Java. Remember the size of byte array tin last to a greater extent than than the length of String because it's non necessary that 1 byte is used to encode 1 character, it all depends on grapheme encoding. For example, UTF-8 is a multi-byte grapheme encoding system as well as uses betwixt 1 to four bytes per character. In general, characters of the quondam ASCII attain takes 1 bytes simply characters from the quondam ISO-8859 attain beyond ASCII takes 2 bytes.
Other articles you may like
The Java Fundamentals: Java linguistic communication yesteryear Jim Wilson
How to supervene upon characters as well as substring inward given String?
How String inward switch instance plant inward Java?
What is the divergence inward String puddle betwixt Java half dozen as well as 7?
When to travel intern() method of String inward Java?
Difference betwixt String literal as well as novel String inward Java?
Difference betwixt String literal as well as novel String inward Java?
10 Difference betwixt StringBuffer as well as StringBuilder inward Java?
Thanks for reading this article, if you lot similar this tutorial as well as then delight portion amongst your friends. If you lot receive got whatever questions or feedback as well as then delight drib us a note.
Thanks for reading this article, if you lot similar this tutorial as well as then delight portion amongst your friends. If you lot receive got whatever questions or feedback as well as then delight drib us a note.

0 Response to "3 ways to convert String to byte array inwards Java - Example Tutorial"
Posting Komentar