tags:

views:

475

answers:

2

I am reading a char array from a file in and then converting it too a string using the String constructor.

read = fromSystem.read(b);
String s = new String(b);

This code has been in the program for ages and works fine, although until now it has been reading the full size of the array, 255 chars, each time. Now I am reusing the class for another purpose and the size of what it reads varies. I am having the problem that if it reads, say 20 chars, then 15, the last 5 of the previous read are still in the byte array. To overcome this I added a null char at the end of what had been read.

read = fromSystem.read(b);
if (read < bufferLength) {
    b[read] = '\0';
}
String s = new String(b);

If I then did

System.out.println(b);

It works, the end of the buffer doens't show. However, if I pass that string into a message dialog then it still shows. Is there some other way that I should terminate the string?

+10  A: 

Use:

String s = new String(b, 0, read)

instead.

atomice
And don't forget to specify the encoding or your application will depend on the platform default encoding, which is usually a very bad idea!
Joachim Sauer
The platform encoding won't be a problem. It is only ever going to run on one computer, if they did change that in the future, they would have much bigger problems.
Android
A: 

You need to use the String constructor that allows you to specify the range of bytes that are valid in the byte array.

String(byte[] bytes, int offset, int length);

Using it like this:

read = fromSystem.read(b);
String s = new String(b, 0, read);
kdubb