How to efficiently convert byte array to string

前端 未结 5 1386
情深已故
情深已故 2020-12-17 18:59

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

相关标签:
5条回答
  • 2020-12-17 19:35

    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.

    0 讨论(0)
  • 2020-12-17 19:37

    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);
    
    0 讨论(0)
  • 2020-12-17 19:43

    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);
    
    0 讨论(0)
  • 2020-12-17 19:46

    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);
    
    0 讨论(0)
  • 2020-12-17 19:50
    new String(b, 0 ,5);
    

    See the API doc for more information.

    0 讨论(0)
提交回复
热议问题