Print string with null character in java

I have a string that contains a null character, i.e. \0. How can I print the whole line in java?

String s = new String("abc\u0000def");
System.out.println(s.length());

System.out.println(s);

Output to the eclipse console:

7
abc

Length is a complete line, but how can I print an entire line?

UPDATE: I use

Eclipse Helios Service Release 2

Java 1.6

+5
source share
3 answers

If Eclipse will not interact, I would suggest replacing null characters with spaces before printing:

System.out.println(s.replace('\u0000', ' '));

If you need to do this in many places, here's a hack to filter them from System.out itself:

import java.io.*;

...

System.setOut(new PrintStream(new FilterOutputStream(
        new FileOutputStream(FileDescriptor.out)) {
    public void write(int b) throws IOException {
        if (b == '\u0000') b = ' ';
        super.write(b);
    }
}));

Then you can usually call the System.out methods with all the data passing through the filter.

+2
source

String char . :

System.out.println(s.toCharArray());

abcdef ().

+3

the correct output of your code using Java 5 or higher

public class TestMain
{
    public static void main(String args[])
    {
        String s = new String("abc\u0000def");
        System.out.println(s.length());
        System.out.println(s);
    }
}

7
abc def

+1
source

All Articles