简体   繁体   English

将不可打印的字符添加到 Java 中的字符串?

[英]Adding non printable chars to a string in Java?

I need to add some non printable chars to a string in java so it can be sent down a tcp pipe.我需要在 java 中的字符串中添加一些不可打印的字符,以便它可以通过 tcp 管道发送。 the chars mean something to the protocol I am using (record separator and end of message respectively)字符对我使用的协议有什么意义(分别是记录分隔符和消息结尾)

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(文本结束)。

public final class ProtocolConstants {
    public final char RECORD_SEPARATOR = 0x1e;
    public final char END_OF_TEXT = 0x03;

    private ProtocolConstants() {}
}

something like that?类似的东西?

If you wish, you can write these as Unicode literals (in chars or Strings):如果您愿意,可以将这些写为 Unicode 文字(以字符或字符串形式):

final String endOfText = "\u0003";

I am assuming that you don't literally want ASCII for a byte-based protocol (the chars are still 16 bits).我假设您实际上并不需要ASCII用于基于字节的协议(字符仍然是 16 位)。

You can add any chars to a Java String .您可以向 Java String添加任何字符。 But a String is probably not what you want if you just want to transmit binary data.但是如果您只想传输二进制数据, String可能不是您想要的。 Consider using a byte[] or some other byte-oriented interface.考虑使用byte[]或其他一些面向字节的接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM