I have a byte array of 151 bytes which is typically a record, The record needs to inserted in to a oracle database. In 151 byte of array range from 0 to 1 is a record id , 2 to 3 is an reference id , 4 to 9 is a date value. The following data in an byte array is a date value. i want to convert it to string
byte[] b= {48,48,49,48,48,52}; // when converted to string it becomes 10042.
new String(b); // current approach
is there any way to efficiently to convert byte array of some range (Arrays.copyOfRange(b,0,5)
) to string .
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
String also has a constructor where we can provide byte array and Charset as an argument. So below code can also be used to convert byte array to String in Java. String str = new String(byteArray, StandardCharsets. UTF_8);
One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java.
new String(b, 0 ,5);
See the API doc for more information.
Use the String(bytes[] bytes, int offset, int length)
constructor: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#String(byte[], int, int)
new String(b, 0, 5);
If you need to create a string for each region in the record, I would suggest a substring approach:
byte[] wholeRecord = {0,1,2 .. all record goes here .. 151}
String wholeString = new String(wholeRecord);
String id = wholeString.substring(0,1);
String refId = wholeString.substring(1,3);
...
The actual offsets may be different depending on string encoding.
The advantage of this approach is that the byte array is only copied once. Subsequent calls to substring()
will not create copies, but will simply reference the first copy with offsets. So you can save some memory and array copying time.
None of the answers here consider that you might not be using ASCII. When converting bytes to a string, you should always consider the charset.
new String(bytes, offset, length, charset);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With