Clear the console in Java - 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();
}

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

why my program never reach the solve method?

sorry if its a stupid question, but I a beginner using StreamTokenizer, I am trying to solve this exercise this, please help me, I dont know what its wrong in my program that never reach my solve method, it also never finishes, I already ask in timus forum, but I know that here is faster to receive an answers
import java.io.*;
public class Prueba {
static int index = 0;
static double[] l = new double[131072];
public static void main(String args[]) throws IOException {
StreamTokenizer str = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
while (((str.nextToken() != StreamTokenizer.TT_EOF))) {
if (str.ttype == StreamTokenizer.TT_NUMBER) {
l[index++] = str.nval;
//System.out.println(str.nval);
// System.out.println(l[0]);
// System.out.println(l[1]);
}
}
solve();
}
public static void solve() {
double res;
for (int i = index - 1; i >= 0; i--) {
res = Math.sqrt(l[i]);
System.out.println(String.format("%.4f\n", res));
}
}
}
You are reading from the standard input, and your code loops until it gets a TT_EOF. To feed a TT_EOF into your program, you need to press Ctrl-D if you're using Unix, or Ctrl-Z followed by Enter if you're using Windows.
You are waiting on System.in, it is blocking on read, ergo, you will never get to EOF so you while loop will continue to wait for input.
As it is, you either need to pipe a file from command line, or enter text on console followed by EOF character. Pressing Ctrl+Z generates EOF in Windows, and pressing Ctrl+D generates EOF in Unix/Linux.
EDIT: If your input is single line you can check for TT_EOL instead of TT_EOF.
You must call eolIsSignificant(true) before entering the loop. This will make sure end-of-line is treated as separate token

java cli running indicator

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);
}

Is there a way to know if a Java program was started from the command line or from a jar file?

I want to either display a message in the console or a pop up, so in case a parameter is not specified, I want to know to which should I display
Something like:
if( !file.exists() ) {
if( fromCommandLine()){
System.out.println("File doesn't exists");
}else if ( fromDoubleClickOnJar() ) {
JOptionPane.showMessage(null, "File doesn't exists");
}
}
The straight forward answer is that you cannot tell how the JVM was launched.
But for the example use-case in your question, you don't really need to know how the JVM was launched. What you really need to know is whether the user will see a message written to the console. And the way to do that would be something like this:
if (!file.exists()) {
Console console = System.console();
if (console != null) {
console.format("File doesn't exists%n");
} else if (!GraphicsEnvironment.isHeadless()) {
JOptionPane.showMessage(null, "File doesn't exists");
} else {
// Put it in the log
}
}
The javadoc for Console, while not water tight, strongly hints that a Console object (if it exists) writes to a console and cannot be redirected.
Thanks #Stephen Denne for the !GraphicsEnvironment.isHeadless() tip.
I'm not clear on the question but I'm going to interpret it as you want to differentiate between the following 2
java -jar fred.jar
and
java package.Main
Here is an outline line of the program
import sun.jvmstat.monitor.*;
...
HostIdentifier hostId = new HostIdentifier("localhost");
MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(hostId);
Set jvms = monitoredHost.activeVms();
for (Object i: jvms) {
VmIdentifier id = new VmIdentifier("//" + i + "?mode=r");
MonitoredVm vm = monitoredHost.getMonitoredVm(id, 0);
System.out.println(i);
System.out.println("\t main class: " + MonitoredVmUtil.mainClass(vm, false));
System.out.println("\t main args: " + MonitoredVmUtil.mainArgs(vm));
System.out.println("\t jvmArgs: " + MonitoredVmUtil.jvmArgs(vm));
monitoredHost.detach(vm);
}
The call MonitoredVmUtil.mainClass(vm, false) will either return 'jar' or the name of your main class eg Main.
You have to use $JAVA_HOME/lib/tools.jar to compile and run.
The System.console() trick seems to do the work.
Here's an alternative: there's a method in the class Class getProtectionDomain() which may be used to know the source of the code the the location from there.
The funny is, this method is available since 1.2
I knew I used this before, here's the original answer by erickson
Here's the proof of concept:
public class FromJar {
public static void main( String [] args ) {
if ( FromJar.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.getFile()
.endsWith(".jar") ) {
javax.swing.JOptionPane.showMessageDialog( null, "Launched from Jar" );
} else {
System.out.println("Launched NOT from Jar :P ");
}
}
}
Here's a short ( 1m aprox ) video to see this code running ( and being written with cat :-o )
You can try with:
if (System.console() != null) {
// Console attached to the JVM: command prompt output
System.out.println("...");
} else {
// No console: use Swing
}
From http://java.itags.org/java-essentials/15972/
try {
GraphicsEnvironment.getLocalGraphicsEnvironment();
} catch(Throwable ex) {
System.out.println("No graphical environment is available.");
}
it's true that it is impossible to tell how the JVM was invoked.
but... there's a way to side step this.
you assumed that when the user double clicked on a JAR, then there's GUI running...
ok. so let's extend this assumption.
check.. from where the class was invoked, the directory.
check that directory..
assuming it's a normal usage, when there's a *.jar file, then the user must've started the app from a jar..
but one flaw is that the user can also click on the main class file.
hahahaha
You can get all the input arguments with RuntimeMBean.getInputArguments(), this can be used to detect when debugging is enabled.
EDIT: However, the -jar argument isn't one of them. :(

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