Recipe 10.12 Those Pesky End-of-Line Characters


Problem

You really want to know about end-of-line characters.

Solution

Use \r and \n in whatever combination makes sense.

Discussion

If you are reading text (or bytes containing ASCII characters) in line mode using the readLine( ) method, you'll never see the end-of-line characters, and so you won't be cursed with having to figure out whether \n, \r, or \r\n appears at the end of each line. If you want that level of detail, you have to read the characters or bytes one at a time, using the read( ) methods. The only time I've found this necessary is in networking code, where some of the line-mode protocols assume that the line ending is \r\n. Even here, though, you can still work in line mode. When writing, pass \r\n into the print( ) (not println( ) !) method. When reading, use readLine( ) and you won't have to deal with the characters:

outputSocket.print("HELO " + myName + "\r\n"); String response = inputSocket.readLine( );

For the curious, the strange spelling of "hello" is used in SMTP, the mail sending protocol, where all commands must be four letters.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net