parse escape character as a byte

11,082

Solution 1

Try this:

private static final byte DELIMITER = (byte) '\n';

Double quotes are for String literals, single quotes for characters, and Byte#valueOf does something else than what you think it does.

If you wanted to turn a String into bytes, you'd do:

byte[] theBytes = "\n".getBytes("UTF-8");

Solution 2

There are plenty of answers to your question, but the next question will be why doesn't my loop work? e.g. if you read exactly 10 bytes long it will stop and if you send two messages at once they will be read in a single read.

What you really want is something like

BufferedReader br = new BufferedReader(new InputStreamReader(in));
for(String line; (line = br.readline()) != null; ) {
    System.out.println("Line read: " + line);
}

Solution 3

Please try this

private static final byte DELIMITER = '\n';

'\n' is of type char which corresponds to unsigned short. But keep in mind that short in Java is always signed.

Solution 4

How about this:

private static final byte DELIMITER = '\n';

Enclosing the newline in single-quotes make a char value, which can be assigned to a byte without any loss of information in this case.

Share:
11,082
ulquiorra
Author by

ulquiorra

Updated on July 01, 2022

Comments

  • ulquiorra
    ulquiorra about 2 years

    I send requests from a client socket to a server socket and i want to differenciate requests(send as a byte array) using a escape character("\n"). I want to have one request per new line exemple :

    "Request1 "
    "Request2"
    "Request3"
    

    In order to do this , i need to convert the "\n" in byte in order to compare the requests like this

        byte[] request= new byte[1024];
        int nextByte;
            while((nextByte=in.read(request))!=DELIMITER)
            {
    
            String chaine = new String( request,0,nextByte);
            System.out.println("Request send from server: " + chaine);
           }
    

    The problm is that i get an number format exception when i am trying to convert "\n" in byte

    private static final byte DELIMITER = Byte.valueOf("\n");
    

    Thank you very much

  • hansvb
    hansvb almost 12 years
    +1, unless this is binary data (which would be weird, as \n is usually used as record separator for text files).
  • ulquiorra
    ulquiorra almost 12 years
    @Peter Lawrey. Indeed , thank you for your help. Thought the read function allow to compare 2 byte data. Does this work for all request line per line ?
  • Vishy
    Vishy almost 12 years
    To read two byte data in binary you can use DataInputStream but you wouldn't use anything like that here.