Question

Hi I am trying to implement the interface SourceStream in my application and overrides the method read(byte[],off,len) and I read the bytes from a server.But I want to convert those byte stream into String for that I used a string object by new String(byte[]) but it asks the initial byte in off and length of the bytes ie len as parameters..Why it is asking like that, as we contain only Strring(bye[])only. can any one help me...Thanks

Was it helpful?

Solution

If you just have a byte[] then you can create a new String via the String(byte[],int,int) constructor provided by the API.

In your case you would do

byte[] myBytes = ("Hello, World!").getBytes();
String myString = new String(myBytes, 0, myBytes.length);
System.out.println(myString);

EDIT: Try something like this:

int readLength = (len > bufSize ? bufSize : len);
for (int i = 0; i < readLength; i++) {
    b[off + i] = buffers[PBuf][PByte];
}
String metaSt = new String(b, 0, readLength);

OTHER TIPS

Just provide 0 as the initial offset and yourArray.Length as the length and you're done. Quite why a method that takes just a byte array isn't provided is anyones guess - probably just to avoid 101 variations of the method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top