Java - Control console output in windows/linux - java

Does Java support controlling the cursor when outputting to a console? For example, I'd like to set the character position, and possibly color, before doing a System.out.print(). Think of the way an application like top writes to the console. Thanks!

You usually do not use system.out to do these things. most applications in *nix use NCURSES (http://en.wikipedia.org/wiki/Ncurses) for this. You can try http://sourceforge.net/projects/javacurses/ if you need something this smart.
However, you can always sysout backspace (\b) characters if you want to delete what you wanted, and hope for the best

Ha. You can still do it in Linux.
Reference this man page for the codes themselves
http://man7.org/linux/man-pages/man4/console_codes.4.html
public class quickTest{
public static void main( String[] args ){
//This will undo the current line by erasing it
//and then putting the curser back at column 1
System.out.println( "Hello.\u001b[1K\u001b[1GHi." );
}
}

Not directly. In the old days ANSI escape sequences was supported, but not anymore.
I would suggest you look into a good Java Curses library supporting Windows. I cannot recommend any :(

Related

How to clear console in Java - Eclipse

How to clear the console after a few statements have been executed/printed in Eclipse. I have used flush() but didn't work though. Just posting the sample code.
System.out.println("execute ");
System.out.println("these set of lines ");
System.out.println("first");
Thread.sleep(2000); // just to see the printed statements in the console
System.out.flush(); // it is not clearing the above statements
The Eclipse Console does not support the interpretation of the clear screen and other ANSI escape sequences which would be required for that. Also, the ANSI Escape in Console Eclipse plug-in does not support clear screen.
In the upcoming Eclipse IDE 2019-12 (4.14) which will be released on December 18, 2019, the interpretation of the backslash (\b) and carriage return (\r) characters can be enabled in the preferences (see Eclipse 4.14 - New and Noteworthy - Control character interpretation in Console View):
System.out is a Stream, it makes no sense to clear a stream.
Eclipse's Console is a view that renders that stream and has richer capabilities (including the ability to clear its visible buffer of the stream's content) but the only way to access that is if you were writing an Eclipse plug-in; general Java code has no knowledge of Eclipse's Console view.
You might be able to achieve something moderately useful via some hacks, but I would not recommend relying on it. Usage of System.out in production code is highly discouraged anyway; use a Logger (such as slf4j and logback) instead. And consider what you're really trying to achieve.
It depends on your console but if it supports ANSI escape sequences, then try this..
final static String ESC = "\033[";
System.out.print(ESC + "2J");
Also, you can print multiple end of lines ("\n") and simulate the clear screen. At the end clear, at most in the unix shell, not removes the previous content, only moves it up and if you make scroll down can see the previous content.
Here is a sample code:
for (int i = 0; i < 50; ++i) System.out.println();
A third option:
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
In case you are talking about eclipse (java console, there is mvn console and svn console as well) then you might want to work with preferences like below:
Go to Window ยป Preferences to show the Preferences dialog
Go to Run/debug and expand it
Select Console
Here you can now set the console related properties.

editing a string using BufferedReader in Java [duplicate]

Say I allow the user to edit something, like the phone number in an Address Book (actually, that's exactly what I'm doing). Is there something that I can add to println that will allow me to insert a variable to display as fully editable text? The assignment that I'm doing this for doesn't actually call for this, but I think it would be cool to have. I'm looking on Google but can't find anything, then again I don't really know what I'm looking for and whether or not I have the correct terms in mind ...
No, not using only what Java provides in the framework. Editing some text would require to
act on key press, which is not possible as in Java the input is buffered (i.e., wait for Enter to be pressed)
to move around in the text you output, which is also not possible
This could be done using some native code (ncurse on linux, ...), using JNI or JNA, but not that easily.
Note that there are some projects that aim to add those functionalities, so if you can use something outside of the core libraries, you could give them a tries... for instance http://code.google.com/p/java-console-api/
There are various options for this, in order of simplicity and portability to features and complexity:
Simply prompt for the information, reading a complete (return-terminated) line of response, and allow the normal terminal input facilities to be used for basic editing.
Use something like the gnu readline library to allow more advanced editing. You still won't have widgets (text input boxes at specific places on screen) as such though. There's a java implementation here: http://java-readline.sourceforge.net/
Use something like ncurses to specifically position the cursor, print text labels, handle keypresses, and implement your own text input box. Not fun.
Use a textual user interface library (TUI), like this one: http://www.bmsi.com/tuipeer/
If you opened a window that looks like the console window, and could react to keypress events, then you could do what you are asking, but, otherwise, if you are just running a program, the program will have ceased executing and returned control to your console, so it can't do anything else.
But, if you use a scriptable version of java you could write your own shell, and then you could do what you are asking, as the shell would not cease executing.
But, that will probably be beyond your course.

Overwriting text on terminal with Java, issue with Console.read*

I know there are hundreds of questions asking how to update already written text on console and I know I can do it printing the \r character.
My issue comes when I use Console.readPassword or Console.readLine which creates a new line and later I can't overwrite it.
I think that my issue isn't related to something special about the Console.read* methods but to new lines. \r goes to the start of the current line, I need to be able to go to the start of the previous N line and start overwriting from there. Or just clear the entire screen.
Any ideas how can I do this?
Thanks.
In principle, this is terminal dependent, and with simple Java means there is no way to do this for all consoles.
Many terminals (at least in unixoid systems) support ANSI-escape sequences, so you can there write something like "\u001B[1;5H" to move the cursor to line 1, columnn 5.

clear screen option in java [duplicate]

This question already has answers here:
How to clear the console?
(14 answers)
Closed 7 years ago.
Is there any option to clear the screen in java as clrscr() in C.
As dirty hacks go, I like msparer's solution. An even dirtier method that I've seen used (I would never do this myself. I swear. Really.) is to write a bunch of newlines to the console. This doesn't clear the screen at all, but creates the illusion of a clear screen to the user.
char c = '\n';
int length = 25;
char[] chars = new char[length];
Arrays.fill(chars, c);
System.out.print(String.valueOf(chars));
If you're talking about a console application, then there isn't a clear screen option AFAIK. A quite dirty option would be to invoke the clear screen command of the underlying OS.
Then it's something like
Runtime.getRuntime().exec("cls");
for Windows or
Runtime.getRuntime().exec("clear");
for a load of other OS. You can find out the OS with System.getProperty("os.name").
If you're talking about the console, then no. Writing to the console is just a special case of an output stream. Output streams don't know anything about the screen, as they can be just as easily redirected to a file or another system device.
For any console which supports ANSI escapes the following would work (would e.g. work in Win98 console).
private final String ANSI_CLS = "\u001b[2J";
....
System.out.print(ANSI_CLS);
System.out.flush();
...
Starting with Win NT this won't work anymore and you can either
Do a JNI call (e.g. like here: Java: Clear console and control attributes
Or write out a bunch of empty lines
Otherwise you are out of luck.
And btw. you must keep in mind that System.out and System.err don't have to be console they could be set to what ever (writing into a file e.g.) an usecase where clearing the screen wouldn't make any sense at all.
On linux, you can do something like:
System.out.println("\f");
You can also use Jcurses
To clear the screen just type:
System.out.print('\u000C');
You can also try ANSI Escape Codes:
If your terminal support them, try something like this:
System.out.print("\033[2J\033[1;1H");
You can include \0333[1;1H to be sure if \0333[2J does not move the cursor in the upper left corner.
More specifically:
033 is the octal of ESC
2J is for clearing the entire console/terminal screen
1;1H moves the cursor to row 1 and column 1
Jansi is an excellent workaround. I am an amateur coder and Jansi is easy to setup especially with Eclipse.
The following is a link to the homepage of Jansi:
http://jansi.fusesource.org/
The following is a link to a site containing a code as a demonstration of AnsiConsole class contained in the Jansi package:
http://www.rgagnon.com/javadetails/java-0047.html
For Windows, Java Console API project provides functionality to determine console size and set cursor position. Clearing the screen is trivial with that. It's a version 0.2 now so it's not exactly production ready, but it works.
Alternatively, you can simply print out some new lines via System.out.println(). 640 should be enough for everybody :-) It's not the same as clearing screen, but for user's intents and purposes it'd do.
you should give a try with JNA and try mapping native libraries:
on linux you must map C functions from ncurses library
on windows you must map functions from both msvcrt and kernel32, as clearly stated here
PS
let me known if you need some sample code

Is it possible to print text that can be edited by the user (for console programs)?

Say I allow the user to edit something, like the phone number in an Address Book (actually, that's exactly what I'm doing). Is there something that I can add to println that will allow me to insert a variable to display as fully editable text? The assignment that I'm doing this for doesn't actually call for this, but I think it would be cool to have. I'm looking on Google but can't find anything, then again I don't really know what I'm looking for and whether or not I have the correct terms in mind ...
No, not using only what Java provides in the framework. Editing some text would require to
act on key press, which is not possible as in Java the input is buffered (i.e., wait for Enter to be pressed)
to move around in the text you output, which is also not possible
This could be done using some native code (ncurse on linux, ...), using JNI or JNA, but not that easily.
Note that there are some projects that aim to add those functionalities, so if you can use something outside of the core libraries, you could give them a tries... for instance http://code.google.com/p/java-console-api/
There are various options for this, in order of simplicity and portability to features and complexity:
Simply prompt for the information, reading a complete (return-terminated) line of response, and allow the normal terminal input facilities to be used for basic editing.
Use something like the gnu readline library to allow more advanced editing. You still won't have widgets (text input boxes at specific places on screen) as such though. There's a java implementation here: http://java-readline.sourceforge.net/
Use something like ncurses to specifically position the cursor, print text labels, handle keypresses, and implement your own text input box. Not fun.
Use a textual user interface library (TUI), like this one: http://www.bmsi.com/tuipeer/
If you opened a window that looks like the console window, and could react to keypress events, then you could do what you are asking, but, otherwise, if you are just running a program, the program will have ceased executing and returned control to your console, so it can't do anything else.
But, if you use a scriptable version of java you could write your own shell, and then you could do what you are asking, as the shell would not cease executing.
But, that will probably be beyond your course.

Categories