在Java中打印具有空字符的字符串 [英] Print string with null character in java
问题描述
我有一个字符串,其中包含空字符,即\0
.如何在Java中打印整个字符串?
I have string which contains null character ie \0
. How can I print the whole string in java?
String s = new String("abc\u0000def");
System.out.println(s.length());
System.out.println(s);
eclipse控制台上的输出:
Output on eclipse console:
7
abc
长度是完整字符串的长度,但是如何打印整个字符串?
Length is that of complete string, but how can I print the whole string?
更新:我正在使用
Eclipse Helios Service Release 2
Java 1.6
推荐答案
如果Eclipse不配合,我建议在打印之前用空格替换空字符:
If Eclipse won't cooperate, I'd suggest replacing the null characters with spaces before printing:
System.out.println(s.replace('\u0000', ' '));
如果您需要在很多地方进行此操作,可以使用以下技巧从System.out自身中过滤掉它们:
If you need to do this in a lot of 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);
}
}));
然后,您可以正常调用System.out方法,所有数据都将通过过滤器.
Then you can call System.out methods normally, with all the data going through the filter.
这篇关于在Java中打印具有空字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!