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).
Inserting ASCII characters To insert an ASCII character, press and hold down ALT while typing the character code. For example, to insert the degree (º) symbol, press and hold down ALT while typing 0176 on the numeric keypad. You must use the numeric keypad to type the numbers, and not the keyboard.
One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer.
The chars() method is an instance method of the String class. It returns an IntStream that consists of the code point values of the characters in the given string. This method was added to the String class in Java 9.
In Java, char and int are compatible types so just add them with + operator. c + x results in an integer, so you need an explicit casting to assign it to your character varaible back.
public final class ProtocolConstants {
public final char RECORD_SEPARATOR = 0x1e;
public final char END_OF_TEXT = 0x03;
private ProtocolConstants() {}
}
something like that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With