1

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?

2 Answers 2

10

Use:

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

instead.

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

2 Comments

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!
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.
1

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

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.