\n
- is a new line in java, is it possible to get to the previous line from the current position?
For example, I want to print "this is for test"
System.out.println("this is for");
Now how can I append "test" to the previous line since println moved carriage to the next?
The newline character, also called end of line (EOL), line break, line feed, line separator or carriage return, is a control character to tell the end of a line of text, and the next character should start at a new line. On the Windows system, it is \r\n , on the Linux system, it is \n . In Java, we can use System.
How do I move cursor to previous line? Press $ to move the cursor to the end of the current line. Moving Down One Line. Press the Return key to move the cursor to the beginning of the next line down.
This works:
print "\033[F\r" + "New String"
The trick is : \033[F
is an ANSI code (which is supported by most terminals) to go back one line. Then, \r
is to go back at the beginning of the line. You can rewrite it from there. You may need to pad it with white spaces to clear it correctly.
I don't think this is supported in the default console in Windows (cmd
), but it is very likely it will work in the powershell. In Linux (and very likely MacOS), should work without any issue.
UPDATE
After 12 years since I posted this answer, it seems \033[F
is no longer working in my tests. Perhaps at that time I did something else that I can't remember now. The \r
works without issues for resetting the position, for example:
static void progress(int current, int total) {
double pp = Math.round((current / total) * 10000) / 100;
System.out.print "\rProgress: " + current + "/" + total + " (" + pp + "%) ";
}
Which you can call in a loop to display a progress.
I don't think you can.
You would normally use System.out.print
for the first part instead and use a println()
or a '\n'
once you're sure your line ended.
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