11

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 .

1
  • @Martjin i have file which has 527890 bytes and i have to read the chunk of 2048 bytes which has 13 records , each record is 151 bytes , and we have to extract the ranges and store in table columns.;) Commented Dec 29, 2010 at 13:38

5 Answers 5

18
new String(b, 0 ,5);

See the API doc for more information.

Sign up to request clarification or add additional context in comments.

1 Comment

@Rekin: no, Suresh specifially does NOT want to use the entire byte array. If he did, it would be much simpler: new String(b)
1

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);

Comments

1

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.

1 Comment

thanks. but u said offset would be different . how to do that dynamically depending upon offset.
1

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);

1 Comment

This is the right answer. (But, even worse than ASCII, that other overload uses the default encoding, which varies from time to time, user to user, system to system.)
-1

and here fantastic way (not efficient) :)

    byte[] b = { 48, 48, 49, 48, 48, 52 };
    ByteArrayInputStream bais = new ByteArrayInputStream(b);

    BufferedReader buf = new BufferedReader(new InputStreamReader(bais));

    String s = buf.readLine();
    System.out.println(s);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.