how to clear console in java (using eclipse) [duplicate] - java

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

Related

Why is System.err.println is printed before then System.out.println?

I was tryingout Logger example from wiki chain of responsibility article.
running the example in idea it prints:
Sending to stderr: An error has occurred.
Writing to stdout: Entering function y.
Writing to stdout: Step1 completed.
Sending via email: Step1 completed.
Writing to stdout: An error has occurred.
Sending via email: An error has occurred.
but when i put a break point in stderrs writeMessage
class StderrLogger extends Logger {
public StderrLogger(int mask) {
this.mask = mask;
}
protected void writeMessage(String msg) {
System.err.println("Sending to stderr: " + msg);//break out here
}
}
it prints all the messags except std err, there is no threads involved here,
then why its printing stderr at first line in run case?.
System.err flushes differently from System.out in Eclipse.
Try this in Eclipse:
public class Derp {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
System.out.println("OUT");
System.err.println("ERR");
}
}
}
This will randomly print out most of the OUTs and most of the ERRs in big chunks. However, this is an Eclipse issue, not a Java issue, as pointed out by Evgeniy Dorofeev.
If you run this sample program in a terminal, you will notice the correct output, without any flushing needed.
Update:
Thanks to Evgeniy Dorofeev for pointing this out!
The flushing not working is an Eclipse problem!
System.out.println -> Sends the output to a standard output stream. Generally monitor.
System.err.println -> Sends the output to a standard error stream. Generally monitor.
The streams out and err are independent.
To get the desired output you must flush the streams or just use just one stream for all outputting.
You can use System.out.flush(); and System.err.flush(); in your code
If you are printing it from Eclipse, it is a known bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=32205

Program provides correct output for println(String s); but not print(String s); why?

Below is a code I'm having issues with:
public class testOutput {
public static void main(String[] args) throws Exception {
int count = 50000;
String s = "Vinjith";
for(int i=0;i<count;i++) {
System.out.print(s); // change this to println(s); and it works!
System.out.flush();
}
}
}
I'm using Eclipse Galileo - jdk 1.6/ jre6.
I've set no limit on the console output.
I've also tried the same program with BufferedWriter: doesn't work
It works when the variable count = 584; not more than that.
I do not get any output when i use System.out.print(s); but when i use System.out.println(s); i get 50000 lines of the string 'Vinjith'.
Thanks.
This is because of having too much characters on the same line, where Eclipse does not support that on its console (You will see nothing printing on the console). Try the same code on the command line and it should work.
This is because the length of the characters you're printing on Eclipse console is going beyond the limits.
Try this and see if it prints or not.
System.out.print(s); // change this to println(s); and it works!
System.out.println();
System.out.flush();
Also, regarding the limit issue, just try this out. In the preferences - > run/debug -> console, there will an check box called Fixed Width Console. Its max limit is 1000. Try to make it 1000 and run your original code as below. You'll see that it prints some characters and for the rest, throws up an Internal Error.
System.out.print(s); // change this to println(s); and it works!
System.out.flush();
Have you tried this:
for(int i=0;i<count;i++) {
System.out.print(s); // change this to println(s); and it works!
}
System.out.println("---done");
System.out.flush();
What happens when you try values of count (100, 500, 1000, 2000, 10000, etc.)?
Please post output from when it works and what 'count' is.
I've looked into issues with flush() before and it comes down to how your OS internally handles buffers. Most JRE's only define the interface and then rely on the OS to implement the actual behavior and in some cases it gets weird. See my answer to a similiar question.

Control program from command line arguments

How do I pick the methods in my program to run using command line arguments? For example, if I want my program to process an image called Moon.jpg, how do I make it work so that -S Moon.jpg in the command line would invoke the Scale method? Or -HI Moon.jpg would flip the image Horizontally and Invert it? I have some methods written and they work when I run the program normally.
You can parse arguments with a function like this:
private void parseArguments(String[] args)
{
int i = 0;
String curArg;
while (i < args.length && args[i].startsWith("-"))
{
curArg = args[i++];
if ("-S".compareTo(curArg) == 0)
{
if (i < args.length)
{
String image = args[i++];
processImage()
}
else
{
// ERROR
}
}
}
}
Your main method should always have String[] args which contains arguments split on the space character. There are also plenty of libraries you can use to parse command line arguments. This method is quite similar to what the Apaches CLI library uses (Of course there's a lot more that comes with that library but the parser uses this logic).
http://commons.apache.org/cli/
This should help. and here's how to use it:
http://commons.apache.org/cli/usage.html
You may need to write different methods for each purpose and have if/else conditions based on command input.
why not read the arguments passed and read subsequent value to do the required stuff
ie,
java yourprogram -a1 something -a2 somethingelse
and in your program
public static void main(String[] args){
for(int i=0;i<args.length;i++){
switch(args[i]){//you can use if-else to deal with string...
case "-a1":read args[i+1] to get value to do somethng
case "-a2": read args[i+1] to get value to do something else
}
}

How to delete stuff printed to console by System.out.println()?

In a Java application I'm using some calls to System.out.println(). Now I want to find a way to programmatically delete this stuff.
I couldn't find any solution with google, so are there any hints?
You could print the backspace character \b as many times as the characters which were printed before.
System.out.print("hello");
Thread.sleep(1000); // Just to give the user a chance to see "hello".
System.out.print("\b\b\b\b\b");
System.out.print("world");
Note: this doesn't work flawlessly in Eclipse console in older releases before Mars (4.5). This works however perfectly fine in command console. See also How to get backspace \b to work in Eclipse's console?
Clearing screen in Java is not supported, but you can try some hacks to achieve this.
a) Use OS-depends command, like this for Windows:
Runtime.getRuntime().exec("cls");
b) Put bunch of new lines (this makes ilusion that screen is clear)
c) If you ever want to turn off System.out, you can try this:
System.setOut(new PrintStream(new OutputStream() {
#Override public void write(int b) throws IOException {}
}));
You could use cursor up to delete a line, and erase text, or simply overwrite with the old text with new text.
int count = 1;
System.out.print(String.format("\033[%dA",count)); // Move up
System.out.print("\033[2K"); // Erase line content
or clear screen
System.out.print(String.format("\033[2J"));
This is standard, but according to wikipedia the Windows console don't follow it.
Have a look: http://www.termsys.demon.co.uk/vtansi.htm
I am using blueJ for java programming. There is a way to clear the screen of it's terminal window. Try this:-
System.out.print ('\f');
this will clear whatever is printed before this line. But this does not work in command prompt.
System.out is a PrintStream, and in itself does not provide any way to modify what gets output. Depending on what is backing that object, you may or may not be able to modify it. For example, if you are redirecting System.out to a log file, you may be able to modify that file after the fact. If it's going straight to a console, the text will disappear once it reaches the top of the console's buffer, but there's no way to mess with it programmatically.
I'm not sure exactly what you're hoping to accomplish, but you may want to consider creating a proxy PrintStream to filter messages as they get output, instead of trying to remove them after the fact.
To clear the Output screen, you can simulate a real person pressing CTRL + L (which clears the output). You can achieve this by using the Robot() class, here is how you can do this:
try {
Robot robbie = new Robot();
robbie.keyPress(17); // Holds CTRL key.
robbie.keyPress(76); // Holds L key.
robbie.keyRelease(17); // Releases CTRL key.
robbie.keyRelease(76); // Releases L key.
} catch (AWTException ex) {
Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex);
}
There are two different ways to clear the terminal in BlueJ. You can get BlueJ to automatically clear the terminal before every interactive method call. To do this, activate the 'Clear screen at method call' option in the 'Options' menu of the terminal. You can also clear the terminal programmatically from within your program. Printing a formfeed character (Unicode 000C) clears the BlueJ terminal, for example:
System.out.print('\u000C');
Just to add to BalusC's anwswer...
Invoking System.out.print("\b \b") repeatedly with a delay gives an exact same behavior as when we hit backspaces in {Windows 7 command console / Java 1.6}
I've found that in Eclipse Mars, if you can safely assume that the line you replace it with will be at least as long as the line you are erasing, simply printing '\r' (a carriage return) will allow your cursor to move back to the beginning of the line to overwrite any characters you see. I suppose if the new line is shorter, you can just make up the different with spaces.
This method is pretty handy in eclipse for live-updating progress percentages, such as in this code snippet I ripped out of one of my programs. It's part of a program to download media files from a website.
URL url=new URL(link);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.connect();
if(connection.getResponseCode()!=HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Response "+connection.getResponseCode()+": "+connection.getResponseMessage()+" on url "+link);
}
long fileLength=connection.getContentLengthLong();
File newFile=new File(ROOT_DIR,link.substring(link.lastIndexOf('/')));
try(InputStream input=connection.getInputStream();
OutputStream output=new FileOutputStream(newFile);)
{
byte[] buffer=new byte[4096];
int count=input.read(buffer);
long totalRead=count;
System.out.println("Writing "+url+" to "+newFile+" ("+fileLength+" bytes)");
System.out.printf("%.2f%%",((double)totalRead/(double)fileLength)*100.0);
while(count!=-1)
{
output.write(buffer,0,count);
count=input.read(buffer);
totalRead+=count;
System.out.printf("\r%.2f%%",((double)totalRead/(double)fileLength)*100.0);
}
System.out.println("\nFinished index "+INDEX);
}
The easiest ways to do this would be:
System.out.println("\f");
System.out.println("\u000c");
For intellij console the 0x08 character worked for me!
System.out.print((char) 8);
I found a solution for the wiping the console in an Eclipse IDE. It uses the Robot class. Please see code below and caption for explanation:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public void wipeConsole() throws AWTException{
Robot robbie = new Robot();
//shows the Console View
robbie.keyPress(KeyEvent.VK_ALT);
robbie.keyPress(KeyEvent.VK_SHIFT);
robbie.keyPress(KeyEvent.VK_Q);
robbie.keyRelease(KeyEvent.VK_ALT);
robbie.keyPress(KeyEvent.VK_SHIFT);
robbie.keyPress(KeyEvent.VK_Q);
robbie.keyPress(KeyEvent.VK_C);
robbie.keyRelease(KeyEvent.VK_C);
//clears the console
robbie.keyPress(KeyEvent.VK_SHIFT);
robbie.keyPress(KeyEvent.VK_F10);
robbie.keyRelease(KeyEvent.VK_SHIFT);
robbie.keyRelease(KeyEvent.VK_F10);
robbie.keyPress(KeyEvent.VK_R);
robbie.keyRelease(KeyEvent.VK_R);
}
Assuming you haven't changed the default hot key settings in Eclipse and import those java classes, this should work.
BalusC answer didn't work for me (bash console on Ubuntu). Some stuff remained at the end of the line. So I rolled over again with spaces. Thread.sleep() is used in the below snippet so you can see what's happening.
String foo = "the quick brown fox jumped over the fence";
System.out.printf(foo);
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul("\b", foo.length()));
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul(" ", foo.length()));
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul("\b", foo.length()));
where mul is a simple method defined as:
private static String mul(String s, int n) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < n ; i++)
builder.append(s);
return builder.toString();
}
(Guava's Strings class also provides a similar repeat method)
I have successfully used the following:
#Before
public void dontPrintExceptions() {
// get rid of the stack trace prints for expected exceptions
System.setErr(new PrintStream(new NullStream()));
}
NullStream lives in the import com.sun.tools.internal.xjc.util package so might not be available on all Java implementations, but it's just an OutputStream, should be simple enough to write your own.
this solution is applicable if you want to remove some System.out.println() output. It restricts that output to print on console and print other outputs.
PrintStream ps = System.out;
System.setOut(new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {}
}));
System.out.println("It will not print");
//To again enable it.
System.setOut(ps);
System.out.println("It will print");

How do I catch a java.io.PrintStream place its output in a JEditorPane?

I am attempting to make a Java program in which a user can select any .class or .jar file from their computer. My program will then pop up a JInternalFrame with a JEditorPane in it as the console, capturing any console output from the user's program. Note that I do not want to capture just System.err or System.out calls, but ALL PrintStream calls that go to the console.
(individual question from IDE-Style program running )
You can catch everything that is printed through System.out using System.setOut like this:
import java.io.*;
class SystemOutLogging {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
final PrintStream original = System.out;
System.setOut(new PrintStream("programlog.txt") {
public void println(String str) {
process(str + "\n");
}
public void print(String str) {
process(str);
}
private void process(String str) {
// Fill some JEditorPane
original.println("Program printed: \"" + str + "\"");
}
});
System.out.print("Hello ");
System.out.println(" World");
}
}
Prints:
Program printed: "Hello "
Program printed: " World
"
(There is a System.setErr and System.setIn that works similarly.)
If you want to catch stuff that the "subprogram" prints through System.out.println you're in trouble, because System.out is a static so if you launch multiple "subprograms" you'll end up with a mess (since you can't hand a separate System class to each subprogram).
In a situation like this, I honestly think it would be a better idea to launch a separate process through ProcessBuilder. The standard input / output streams of the resulting process could easily be logged.
(p.s. When I think about it, you could probably check the current thread group in the println implementation, and from that decide which subprogram that actually invoked the println method)
If you're starting the user's .jar file using Runtime.exec(), you'll get a Process object. That Object will allow you access to the launched processes System.out, System.in and System.err streams.
See: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html
You can take read from the err and out streams, and append to your JEditorPane using the usual setText type methods.

Categories