Alex Rivera | Logout

Is it possible to add data to a string after adding "\0" (null)?

Asked 2011-12-24T09:12:54.447
10

I have a string that I am creating, and I need to add multiple "\0" (null) characters to the string. Between each null character, is other text data (Just ASCII alphanumeric characters).

My problem is that in J2SE when you add the first null (\0), java then seems to determine that it's a string terminator, (similar to C++), and ignores all other data being appended. No error is raised, the trailing data is just ignored. I need to force the additional trailing data after a null in the string. I have to do this for a legacy database that I am supporting.

I have tried to encode/decode the string in hoping that something like %00 would fool the interpretation of the string behaviour, but when I re-encode the string, Java sees the null character again, and removes all data after the first null.

Update: Here is the relevant code snippet. Yes, I am trying to use Strings. I intend to try chars, but I still have to save it into the database as a string, so I suspect that I will end up with the same problem.

Some background. I am receiving data via HTTP post that has "\n". I need to remove the newlines and replace them with "\0". The "debug" method is just a simple method that does System.out.println.

                String[] arrLines = sValue.split("\n");
                for(int k=0;k<arrLines.length;k++) {
                    if (0<k) {
                        sNewValue += "\0";
                    }
                    sNewValue+= arrLines[k];
                    debug("New value =" + sNewValue);
                }

sNewValue, a String, is committed to the database and needs to be done as a String. What I am observing when i display the current value of sNewValue after each iteration in the console is something like this:

input is value1\nValue2\nValue3 Output in the console is giving me from this code

value1
value1
value1

                    
                    
                    
Edit
Report

1 Answer

1

Same behavior for the StringBuffer class?

Since "\0" makes some trouble, I would recommend to not use it. I would try to replace some better delimiter with "\0" when actually writing the string to your DB.

answered 2011-12-24T09:31:12.137

Your Answer