Thursday, November 22, 2012

Print a carriage return in java on windows




I need to print :q in a new line. I’m using a StringBuffer which prints a new line in this format

StringBuffer sBuffer = new StringBuffer();
sBuffer.append(String.format("Hello"));
sBuffer.append(String.format("\n"));
sBuffer.append(String.format(":q"));


The program works fine in Windows XP. :q will be printed in a new line when the program is executed.
Hello
:q


But in Windows 7, :q is printed in the same line.

Hello:q

The issue here is:
Different operating systems use different line separators.
In Java, \r is always carriage return, and \n is line feed. On Unix, just \n is enough for a newline, whereas many programs on Windows require \r\n. So you will have to modify the program like this to work on Windows 7.

StringBuffer sBuffer = new StringBuffer();
sBuffer.append(String.format("Hello"));
sBuffer.append(String.format("\r\n"));
sBuffer.append(String.format(":q"));

No comments:

Post a Comment

Thanks for visiting my Blog....Ur comments n suggestions are most valuable for me...Thanks