简体   繁体   中英

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. 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.

For the curious the chars I need are ASCIIx1E (Record separator) and ACSIIx03 (End of Text).

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):

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).

You can add any chars to a Java String . But a String is probably not what you want if you just want to transmit binary data. Consider using a byte[] or some other byte-oriented interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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