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
Is there a way to clear IntelliJ console from code? I've tried all the solutions I've found, like:
Runtime.getRuntime().exec("clear")
System.out.print("\033[H\033[2J");
System.out.flush();
even printing a lot of "\b"s just prints a odd char instead of erasing the output.
Printing a lot of "\n" doesn't work for me, for two reasons:
you are still able to scroll up;
pointer is not placed at the beginning of the console.
I just need to trigger the console "Clear All" button (the little trashcan icon), but from within the code. Every hack is well accepted.
I "hacked" it by literally clicking the "Clear All" icon:
public static void click(int x, int y) throws AWTException{
Robot bot = new Robot();
bot.mouseMove(x, y);
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
}
calling this with these coordinates on my screen:
click(75,890);
IntelliJ IDEA console is not a real terminal, so there is no command to clear it from your Java code.
Try run your application in other console and you can make a function like this:
public static void ClearConsole(){
try{
String operatingSystem = System.getProperty("os.name") //Check the current operating system
if(operatingSystem.contains("Windows")){
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "cls");
Process startProcess = pb.inheritIO.start();
startProcess.waitFor();
} else {
ProcessBuilder pb = new ProcessBuilder("clear");
Process startProcess = pb.inheritIO.start();
startProcess.waitFor();
}
}catch(Exception e){
System.out.println(e);
}
}
The command "cat ~/desktop/b.mpg ~/desktop/b2.mpg > ~desktop/intermediate_all.mpg" does not seem to work via Java Runtime alone (as seen in the example below);
public class Test {
public static void main(final String[] args) {
String[] cmd = {"cat ~/desktop/b.mpg ~/desktop/b2.mpg > ~desktop/intermediate_all.mpg"};
try { Runtime.getRuntime().exec(cmd); }
catch (IOException e) { e.printStackTrace();}
}
}
However, when put into a .sh file like in this second example it works just fine....
public class Test {
public static void main(final String[] args) {
try { Runtime.getRuntime().exec("/users/nn/desktop/configure.sh"); }
catch (IOException e) { e.printStackTrace();}
}
}
Can anybody please tell me what the fundamental process is being lost when moving from a bash script to straight Java Runtime? FYI, I am using OSX, have already tried using absolute filepaths, and know about Process Builder (which has the same effect) is preferred to using Java Runtim--as has been stated a thousand times on this forum already, so lets avoid beating the dead horse on that one.
Thanks
The command being executed is cat with arguments. The command and its arguments must be separate elements of the array.
Also, you can't redirect using Runtime.exec() - you must use ProcessBuilder:
Try this:
ProcessBuilder pb = new ProcessBuilder("cat", "~/desktop/b.mpg", "~/desktop/b2.mpg");
pb.redirectOutput(new File("~/desktop/intermediate_all.mpg"));
Process p = pb.start();
It is likely that the shell location ~ will not be understood, so you may have to use the full absolute path for the files
Try this:
Runtime.getRuntime().exec(new String[] {
"/bin/bash", "-c",
"cat ~/desktop/b.mpg ~/desktop/b2.mpg > ~/desktop/intermediate_all.mpg" })
Because in the second case, you are effectively running "bash", "-c", "cat etc >file" where Bash takes care of parsing the redirection for you. Redirection is a feature of the shell, not of cat; if you run the raw process without a shell, the features of the shell are not available to you.
in your java code
~/desktop/b.mpg ~/desktop/b2.mpg > ~desktop/intermediate_all.mpg ,
you have to give full path after > ~/desktop/intermediate_all.mpg
I'm trying to make a simple java program to unhide the ~\Library\ folder on osx using terminal commands. As far as I have researched the code to run system commands from java is
Runtime.getRuntime().exec();
and is listed as such in every place I look it up.
However, my program doesn't work. Main method below.
public static void main(String[] args) throws IOException {
String[] noHide = {"chflags"," " ,"nohidden"," ", "~/Library/"};
try {
Runtime.getRuntime().exec(noHide);
System.out.println("library unhidden");
} catch (Exception e ) {
e.printStackTrace();
}
}
This program throws no exception, and compiles and executes fine, but the Library folder simply won't unhide. No matter what I reformat the cmd String. None of the formats below work
String noHide = "chflags nohidden ~/Library";
String[] noHide = {"chflags", "nohidden","~/Library"};
String[] noHide = {"chflags"," " ,"nohidden"," ", "~/Library/"};
If I remove the spaces they throw exceptions (well, not the String array objects). I can run the command (chflags noHidden ~/Library) absolutely fine from the osx terminal. Anyone have an idea why?
You need to use a try and catch, which you have. But, your main should be like this:
public static void main(String[] args) {
String[] noHide = {"chflags", "nohidden","~/Library"};
try {
Runtime.getRuntime().exec(noHide);
}
catch (Exception e) {
}
}
Basically, you don't need throws IOException. This worked for me, so if it still isn't working in your program, there may be a bigger problem with the way you have something set up.
I would like to be able to launch VI from within my Java program and wait for the user to quit VI before proceeding. Here's the code snippet that I have currently:
...
String previewFileName="test.txt"; // the file to edit
CommandLine cmdLine = new CommandLine("/usr/bin/vi");
cmdLine.addArgument(previewFileName);
cmdLine.addArgument(">/dev/tty");
cmdLine.addArgument("</dev/tty");
Executor executor = new DefaultExecutor();
try
{
DefaultExecuteResultHandler resultHandler = new ResetProcessResultHandler(cmdLine);
executor.execute(cmdLine, resultHandler);
} catch (IOException e)
{
throw new Error("Cannot execute command: /usr/bin/vi " + previewFileName, e);
}
log.info("waiting...");
cmdLine.wait();
log.info("...done");
...
private class ResetProcessResultHandler extends DefaultExecuteResultHandler
{
private final CommandLine mCommandLine;
public ResetProcessResultHandler(CommandLine pCommandLine)
{
mCommandLine = pCommandLine;
}
public void onProcessComplete(int exitValue)
{
log.info("Command complete rc(" + exitValue + ")");
if (exitValue != 0)
{
throw new RuntimeException("VI command error [rc=" + exitValue + "] " );
}
mCommandLine.notify();
}
public void onProcessFailed(ExecuteException e)
{
if (e.getExitValue() != 0)
{
log.error("launch VI error " + e.toString());
throw new RuntimeException("VI command failed [" + e.getCause() + "] ");
}
else
{
log.info("VI complete rc(" + e.getExitValue() + ")");
}
mCommandLine.notify();
}
}
I receive output:
Vim: output is not to a terminal
Vim: input is not from a terminal
But then I see the screen painted as if VI had started; and VI doesn't read characters I type.
So ... redirecting from /dev/tty isn't doing the trick.
Someone must have done this before - help!
Thanks,
Mark
However since Java 1.7 you can use the next example to transparently redirect and have full console functionality
System.out.println("STARTING VI");
ProcessBuilder processBuilder = new ProcessBuilder("/usr/bin/vi");
processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT);
Process p = processBuilder.start();
// wait for termination.
p.waitFor();
System.out.println("Exiting VI");
This will allow you to open VI transparently for JVM 1.7+.
When Java runs a program via Runtime.exec() (and this is what commons-exec does in the end), it connects the program's input, output and error streams to your Java app as input/output streams. Such a stream is certainly not a terminal, you can't for example move the text cursor in it (since it doesn't have any), change text colors, or detect if Shift key is pressed (since it's just a stream of bytes and not a physical keyborad). So, an interactive app like vi can't really function under such conditions like in a terminal.
By the way, I'm not sure if the command line args you supply are parsed by the shell or passed directly to the program. In the latter case your redirection to /dev/tty couldn't possibly work even if there was a way for Java to somehow allow the program to replace Java's connected streams with something else.
As an aside, it seems a bit strange why you would like to run vi from inside a Java program.
So I guess the best solution is to execute a terminal emulator like konsole or gnome-terminal or xterm and let it run vi by passing corresponding argument on its command line (e.g. konsole -e vi). In this case the terminal's window should pop up and vi could function inside it. Of course, it won't work if you're on a headless server, but then running vi can't be useful anyway.
I'm not sure how to do it with commons-exec,
But standard Java should be something along the lines of...
String[] command = {"/usr/bin/vi", "test.txt"};
Process vimProcess = Runtime.getRuntime().exec(command);
vimProcess.waitFor();
This will cause the current thread to wait for the process to complete. You can also use
vimProcess.getInputStream(), getOutputStream() and getErrorStream() to redirect those to log files or wherever you want it to go.
See here for more details.
http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html
Hopefully this helps.
I want to output the result of the "dir" command to the java console. I have already looked on Google and here, but none of the examples work for me, thus making me rite this post.
My code is as follows:
try
{
System.out.println("Thread started..");
String line = "";
String cmd = "dir";
Process child = Runtime.getRuntime().exec(cmd);
//Read output
BufferedReader dis = new BufferedReader( new InputStreamReader(child.getInputStream() ));
while ((line = dis.readLine()) != null)
{
System.out.println("Line: " + line);
}
dis.close();
}catch (IOException e){
}
What am I doing wrong?
Any help would be very nice.
Thanks in advance,
Darryl
You cannot run "dir" as a process, you need to change it to String cmd = "cmd dir";.
You don't handle the exception at all. adding the line e.printStackTrace()); in the catch block would tell you what I wrote in (1). Never ignore exceptions!
You don't handle error stream. This might cause your program to hang, handle error stream and read from both streams (error and input) in parallel using different streams.
The best way is to use commons exec http://commons.apache.org/exec/
This has things that catch quirks that can really drive you up the wall, such as the whole process blocking if you didn't clear its output stream, escaping quotes in commands, etc.
Here is a method that will run the del command in windows successfully. Note the use of cmd since del is not a standalone executable:
private void deleteWithCmd(File toDelete) throws IOException {
CommandLine cmdLine = new CommandLine("cmd.exe");
cmdLine.addArgument("/C");
cmdLine.addArgument("del");
cmdLine.addArgument(toDelete.getAbsolutePath());
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(cmdLine);
}
a) What is the java console?
b) You should use javas File.listFiles () instead of Runtime.exec, which isn't portable, and makes Name splitting neccessary - a hard thing, for filenames which contain spaces, blanks, newlines and so on.
c) Whats wrong with your code?
d) Why don't you do anything in the case of Exception?
Here is a more thorough example that accounts for OS versions and error conditions ( as stated by MByD above)
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
Remember that using "exec" means that your application is no longer cross-platform and loses one of the main advantages of Java.
A better approach is to use java.io package.
http://download.oracle.com/javase/tutorial/essential/io/dirs.html
You can also do something like that in java 6 :
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class ListFilesFromRegExp {
public static void main(String[] args) throws IOException {
File dir = new File("files/");
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches("File[0-9].c");
}
});
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getAbsolutePath());
}
}
}