将不可打印的字符添加到 Java 中的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1164703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding non printable chars to a string in Java?
提问by Omar Kooheji
I need to add some non printable chars to a string in java so it can be sent down a tcp pipe. the chars mean something to the protocol I am using (record separator and end of message respectively)
我需要在 java 中的字符串中添加一些不可打印的字符,以便它可以通过 tcp 管道发送。字符对我使用的协议有什么意义(分别是记录分隔符和消息结尾)
what is the best way to go about doing this?
这样做的最佳方法是什么?
Ideally I'l like to refer to them as constants so that I can use string concatonation/stringbuilder/string.format to add them where required, without having to type them out.
理想情况下,我喜欢将它们称为常量,以便我可以使用字符串连接/stringbuilder/string.format 将它们添加到需要的地方,而无需将它们键入。
For the curious the chars I need are ASCIIx1E (Record separator) and ACSIIx03 (End of Text).
对于好奇,我需要的字符是 ASCIIx1E(记录分隔符)和 ACSIIx03(文本结束)。
回答by dfa
public final class ProtocolConstants {
public final char RECORD_SEPARATOR = 0x1e;
public final char END_OF_TEXT = 0x03;
private ProtocolConstants() {}
}
something like that?
类似的东西?
回答by McDowell
回答by newacct
You can add any chars to a Java String. But a Stringis probably not what you want if you just want to transmit binary data. Consider using a byte[]or some other byte-oriented interface.
您可以向 Java 中添加任何字符String。但是String如果您只想传输二进制数据,a可能不是您想要的。考虑使用一个byte[]或其他一些面向字节的接口。

