java cli running indicator - java

I want some ascii characters periodically changing to indicate my CLI program is running, like -|\/-|/.... The old character is replaced by the new, which looks like an animation. Is there any library approaching that?
Kejia

You might want to use the carriage return(CR) character ('\r' in java) to do this. I would do it this way (assuming you are doing the animation at the beginning of the row):
My solution (Test.java):
public class Test
{
public static void main(String[] args)
{
try
{
System.out.print("\\");
Thread.sleep(1000);
System.out.print("\r|");
Thread.sleep(1000);
System.out.print("\r/");
}catch(Exception e)
{
}
}
}

Simplest idea: try replace all console (rows & cols) with new view (frame) of your animation.

I once wrote a test program and part of it worked like curl/wget to download a file. To print the progress I just used System.err.print(n); System.err.print('\r'); which moves the cursor to the start of the line ready for the next progress update. But in your case you could probably print each one of "\\\b" "-\b" "/\b" (\b is backspace) in order repetitively to get the spinning effect.

In Scala:
"-|\\/-|/".toCharArray ().foreach {c => print ("\b" + c); Thread.sleep (250); }
Analog, but more Code in Java, but not tested:
for (c : "-|\\/-|/".toCharArray ())
{
System.out.print ("\b" + c);
Thread.sleep (250);
}

Related

How do I get my code to loop then clear screen of the previous result in Java? [duplicate]

Can any body please tell me what code is used for clear screen in Java?
For example, in C++:
system("CLS");
What code is used in Java to clear the screen?
Since there are several answers here showing non-working code for Windows, here is a clarification:
Runtime.getRuntime().exec("cls");
This command does not work, for two reasons:
There is no executable named cls.exe or cls.com in a standard Windows installation that could be invoked via Runtime.exec, as the well-known command cls is builtin to Windows’ command line interpreter.
When launching a new process via Runtime.exec, the standard output gets redirected to a pipe which the initiating Java process can read. But when the output of the cls command gets redirected, it doesn’t clear the console.
To solve this problem, we have to invoke the command line interpreter (cmd) and tell it to execute a command (/c cls) which allows invoking builtin commands. Further we have to directly connect its output channel to the Java process’ output channel, which works starting with Java 7, using inheritIO():
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
Now when the Java process is connected to a console, i.e. has been started from a command line without output redirection, it will clear the console.
You can use following code to clear command line console:
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
Caveats:
This will work on terminals that support ANSI escape codes
It will not work on Windows' CMD
It will not work in the IDE's terminal
For further reading visit this
This is how I would handle it. This method will work for the Windows OS case and the Linux/Unix OS case (which means it also works for Mac OS X).
public final static void clearConsole()
{
try
{
final String os = System.getProperty("os.name");
if (os.contains("Windows"))
{
Runtime.getRuntime().exec("cls");
}
else
{
Runtime.getRuntime().exec("clear");
}
}
catch (final Exception e)
{
// Handle any exceptions.
}
}
⚠️ Note that this method generally will not clear the console if you are running inside an IDE.
A way to get this can be 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();
Try the following :
System.out.print("\033\143");
This will work fine in Linux environment
Create a method in your class like this: [as #Holger said here.]
public static void clrscr(){
//Clears Screen in java
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
This works for windows at least, I have not checked for Linux so far. If anyone checks it for Linux please let me know if it works (or not).
As an alternate method is to write this code in clrscr():
for(int i = 0; i < 80*300; i++) // Default Height of cmd is 300 and Default width is 80
System.out.print("\b"); // Prints a backspace
I will not recommend you to use this method.
If you want a more system independent way of doing this, you can use the JLine library and ConsoleReader.clearScreen(). Prudent checking of whether JLine and ANSI is supported in the current environment is probably worth doing too.
Something like the following code worked for me:
import jline.console.ConsoleReader;
public class JLineTest
{
public static void main(String... args)
throws Exception
{
ConsoleReader r = new ConsoleReader();
while (true)
{
r.println("Good morning");
r.flush();
String input = r.readLine("prompt>");
if ("clear".equals(input))
r.clearScreen();
else if ("exit".equals(input))
return;
else
System.out.println("You typed '" + input + "'.");
}
}
}
When running this, if you type 'clear' at the prompt it will clear the screen. Make sure you run it from a proper terminal/console and not in Eclipse.
Runtime.getRuntime().exec(cls) did NOT work on my XP laptop. This did -
for(int clear = 0; clear < 1000; clear++)
{
System.out.println("\b") ;
}
Hope this is useful
By combining all the given answers, this method should work on all environments:
public static void clearConsole() {
try {
if (System.getProperty("os.name").contains("Windows")) {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
else {
System.out.print("\033\143");
}
} catch (IOException | InterruptedException ex) {}
}
Try this: only works on console, not in NetBeans integrated console.
public static void cls(){
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c",
"cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
This will work if you are doing this in Bluej or any other similar software.
System.out.print('\u000C');
You can use an emulation of cls with
for (int i = 0; i < 50; ++i) System.out.println();
You need to use control characters as backslash (\b) and carriage return (\r). It come disabled by default, but the Console view can interpret these controls.
Windows>Preferences and Run/Debug > Console and select Interpret ASCII control characteres to enabled it
After these configurations, you can manage your console with control characters like:
\t - tab.
\b - backspace (a step backward in the text or deletion of a single character).
\n - new line.
\r - carriage return. ()
\f - form feed.
More information at: https://www.eclipse.org/eclipse/news/4.14/platform.php
You need to use JNI.
First of all use create a .dll using visual studio, that call system("cls").
After that use JNI to use this DDL.
I found this article that is nice:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=5170&lngWId=2

Clear the console in Java

I have a class extending the Thread class. In its run method there is a System.out.println statement. Before this print statement is executed I want to clear the console. How can I do that?
I tried
Runtime.getRuntime().exec("cls"); // and "clear" too
and
System.out.flush();
but neither worked.
Are you running on a mac? Because if so cls is for Windows.
Windows:
Runtime.getRuntime().exec("cls");
Mac:
Runtime.getRuntime().exec("clear");
flush simply forces any buffered output to be written immediately. It would not clear the console.
edit Sorry those clears only work if you are using the actual console. In eclipse there is no way to programmatically clear the console. You have to put white-spaces or click the clear button.
So you really can only use something like this:
for(int i = 0; i < 1000; i++)
{
System.out.println("\b");
}
You can try something around these lines with System OS dependency :
final String operatingSystem = System.getProperty("os.name");
if (operatingSystem .contains("Windows")) {
Runtime.getRuntime().exec("cls");
}
else {
Runtime.getRuntime().exec("clear");
}
Or other way would actually be a bad way but actually to send backspaces to console till it clears out. Something like :
for(int clear = 0; clear < 1000; clear++) {
System.out.println("\b") ;
}
Here is an example I found on a website hope it will work:
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}

Are empty loops okay to use?

I'm working on a text based game with a GUI as the "console" for input and output. My objective is to, when the game asks for it, submit a command I have typed in a JTextArea to another method.
To do this I have come up with this idea: when user.readLine() is called, it loops until the GUI receives an action event. Detection of this event is accomplished by the flipping of a boolean called commanded, toggled in the actionevent's method. readLine() then breaks the loop at this point and returns the text that was just entered, then flips the boolean back. Interestingly enough, this only works if I add a System.out.println(); or a Thread.sleep(1); before flipping the boolean back...
The readLine() method involves a lot of looping with no code between the braces, as it waits for the Action Event. Is it wrong to think of this as a "short circuit" and something to be avoided? Code is below. Thanks!
CommandInput.java:
public void waitForCommand() {
try {
processCommand(Parasite.user.readLine().toLowerCase());
} catch (Exception e) {
System.err.println(e);
}
}
UI.java (initialized as Parasite.user):
boolean commanded= false;
String command = "";
public final String readLine()
{
while(commanded == false)
{
System.err.print(command);
}
System.out.println("Submitting Command");
commanded = false;
return command;
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
commanded=true;
command=jTextField1.getText();
System.err.println(jTextField1.getText());
jTextField1.setText("");
}
The short circuit thing:
Loops that don't do much in words of other than looping like this:
while(true) {}
are not very CPU friendly, much better would be soemthing like this:
while(true) {
Thread.yield();
}
This says the CPU, that this thread can be stopped right now, so other threads can run now, it gets moved down in the Thread queue. You don't loose that much of precision doing this, but it prevents you from using all of your cpu. (look here for more information: http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#yield() )
So in your case:
while(commanded == false)
{
System.err.print(command);
Thread.yield();
}
Read this article on how to use event driven programming to solve your problem. In short, your approach is inefficient and does not scale well

Break an infinite loop

i have an infinite loop something like that:
while(true) {
//do something
}
I would like to be able to break the loop using a key for exaple escape key. I think it could be done using events but as i am new to java i cant do that.
Can anyone help me? Thank you in advance!
In the while loop the program reads a value from usb and then send it over the network using sockets. My program is the server and sends bytes to a client. I want to be able to stop that server with a key!
In the while loop the program reads a value from usb and then send it over the network using sockets. My program is the server and sends bytes to a client. I want to be able to stop that server with a key!
Pure java, by itself, does not have a notion of a key input. You usually get them from a specific IO module (e.g., console based, AWT based, Swing based, etc.).
You would then check for the condition or break.
If your notification of a press is asynchronous, you would probably set some flag (e.g., breakRequested), and check for this flag and break if it has changed.
For Console access, take a look at http://download.oracle.com/javase/6/docs/api/java/io/Console.html
but pay attention to the many questions about this facility here on Stackoverflow.
Use the break keyword. For example:
try {
Console console = new Console();
while(true)
{
String input = console.readLine();
if("quit".equals(input))
{
break;
}
// otherwise do stuff with input
}
catch(IOException e)
{
// handle e
}
Many programmers think the following would be more readable:
try
{
Console console = new Console();
for(String input = console.readLine(); !"quit".equals(input); input = console.readLine())
{
// do stuff with input
}
}
catch(IOException e)
{
// handle e
}
change while(true) to something like while(!isStopped()){...}
Keep in mind, while your application is in that block, and is spinning, no other portion of your application will be able to process instructions. That is unless you spin off your worker process into a new thread and share a variable/flag between the two. That way, when a key is pressed, through whatever means you have in capturing it, you can modify a boolean variable which will carry over to your thread. So you can set your loop up like the following:
while(_flag)
{
//Spin
}
I have created this program that terminates an infinite loop if a specific key is pressed:
class terminator {
public static void main(String args[]) throws java.io.IOException {
char press, clear;
for(;;) {
System.out.print("Press any key to get display, otherwise press t to terminate: ");
press = (char)System.in.read();
System.out.println("You Pressed: "+ press);
do {
clear = (char)System.in.read();
} while(clear != '\n');
System.out.println("\n");
if (press=='t'|press=='T') {
System.out.println("Terminating Program......Program Terminated!");
break;
}
}
}
}
To break infinite loop with a condition.
public class WhileInf {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) {
break;
}
System.out.println("Hello");
i++;
}
}
}
You can force quit the console if you are in infinite loops.
Window = Ctrl + Shift + Esc
Mac = Option + Command + Esc
while(true)
{
if( )
{
break;
}
else if()
{
break;
}
else
{
do something;
break;
}
}

How can I make the display of a line in my command-line java program change without displaying a new line?

I'm making a java command line program.
How can I change the contents of a line I've already displayed?
So, for example I could display:
Status: 0%
Status: 2%
...
Status: 50%
Except, rather than continuing to push down each new line, I simply change the contents of the existing line, so the % done changes in place.
I've seen some console programs do this before, so how can I do it in java?
In most cases, you can output a carriage return (\r) rather than a newline (\n). This depends on the terminal supporting it, which most do. \r moves the cursor back to the beginning of the line.
EDIT: Obviously, when doing this, use System.out.print rather than System.out.println (or just generally use the plain, not ln, form of the output method you're using) -- since the ln suffix means that your text is automatically followed with a newline.
Example:
for (n = 10000; n < 10010; ++n) {
System.out.print(String.valueOf(n) + "\r");
}
System.out.println("Done");
When this finishes, you'll probably have this on your console screen:
Done0
...since "Done" is shorter than the longest previous thing you output, and so didn't completely overwrite it (hence the 0 at the end, left over from "10010"). So the lesson is: Keep track of the longest thing you write and overwrite it with spaces.
Take a look at this example.
Working code:
public class progress {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i <= 100; i++) {
Thread.sleep(30);
System.out.print("\rSTATUS: "+i+" % " );
}
}
}
Tip: For more Google - java console progress bar

Categories

Resources