Hi i have a StringBuffer object and i want to append a line feed or a carraige return to it. Could someone tell me the code to do this please thanks in advance frank
Carl Trusiak
Sheriff
Joined: Jun 13, 2000
Posts: 3340
posted
0
Originally posted by Frank Daly: Hi i have a StringBuffer object and i want to append a line feed or a carraige return to it. Could someone tell me the code to do this please thanks in advance frank
Line feed is char 0x000A and Carriage Return is char 0x000D to add these to your StringBuffer simply use append(char) so.... StringBuffer sb = new StringBuffer("Hello"); sb.append(0x000A); // for line feed sb.append(0x000D); //for carrage return Now in java, there are two escape characters for these line feed = '\n' carriage return '\r' And so it becomes sb.append('\n'); sb.append('\r'); if you wish to have both, sb.append("\n\r");
ALl the above is true, but please be careful with this. If you are generating a file to be stored on the system and read by other software it is strongly recommended that you add the appropriate end-of-line characters for the platform you are running on. Unix systems use just a linefeed (\n), Dos and Windows use carriage return land inefeed (\r\n), Others use just a carraige return, or lifefeed then carriage return ... Luckily Java provides System.getProperty("line.separator") which gives you a String containing the appropriate end-of-line sequence, so you can just do: <pre> StringBuffer sb = new StringBuffer("Hello"); sb.append(System.getProperty("line.separator")); </pre> which will then work on any platform. This is an important part of making your program "100% Pure Java"