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 alphanume
I strongly suspect this is nothing to do with the text in the string itself - I suspect it's just how it's being displayed. For example, try this:
public class Test {
public static void main(String[] args) {
String first = "first";
String second = "second";
String third = "third";
String text = first + "\0" + second + "\0" + third;
System.out.println(text.length()); // Prints 18
}
}
This prints 18, showing that all the characters are present. However, if you try to display text
in a UI label, I wouldn't be surprised to see only first
. (The same may be true in fairly weak debuggers.)
Likewise you should be able to use:
char c = text.charAt(7);
And now c
should be 'e'
which is the second letter of "second".
Basically, I'd expect the core of Java not to care at all about the fact that it contains U+0000. It's just another character as far as Java is concerned. It's only at boundaries with native code (e.g. display) that it's likely to cause a problem.
If this doesn't help, please explain exactly what you've observed - what it is that makes you think the rest of the data isn't being appended.
EDIT: Another diagnostic approach is to print out the Unicode value of each character in the string:
for (int i = 0; i < text.length(); i++) {
System.out.println((int) text.charAt(i));
}
I suggest you use a char[]
or List<Char>
instead since it sounds like you're not really using a String
as such (a real String doesn't normally contain nulls or other unprintable characters).
This is because \
is an escape character in Java (as in many C-related languages) and you need to escape it using additional \
as follows.
String str="\\0Java language";
System.out.println(str);
and you should be able the display \0Java language on the console.
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.