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);
}
}
Related
I am currently working on a project that allows users to enter an IP Address and a file name, then run Logcat to save the file to the user entered file name.
The UI
The Application will allows users to start writing logs, and stop writing logs with a start and stop button. On the bottom there will be a status textfield that updates the user with the status of the ADB Command.
The command I am using to retrieve the Logs is adb logcat > (filename).txt
Currently, I have the logging working perfectly fine at the push of the start button.
Logging
onStartButtonClick Method
#FXML
protected void onStartButtonClick() {
ipAddress = deviceIP.getText();
nameFile = fileName.getText();
if(nameFile == null || nameFile.equals("")){
createDialog("Please Enter Valid File Name");
return;
}
if(ipAddress == null || ipAddress.equals("")){
createDialog("Please Enter Valid IP");
return;
}
runCommands("adb connect "+ipAddress, "Connecting to IP Address");
runCommands("adb logcat > "+nameFile+".txt", "Logging IP: "+ipAddress);
}
My On start button click method passes the user entered data to a method I have that actually executes the commands.
runCommands Method
#FXML
public void runCommands(String command, String status){
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", command);
try {
builder.redirectErrorStream(true);
p = builder.start();
r = new BufferedReader(new InputStreamReader(p.getInputStream()));
spinner.setOpacity(100);
loggingStatus.setText(status);
startButton.setDisable(true);
stopButton.setDisable(false);
Thread t = new Thread(() -> {
threadRunning = true;
while(threadRunning){
try {
line = r.readLine();
}
catch (Exception e){
System.err.println(e);
}
if (line == null) {
break;
}
}
});
t.start();
}
catch (Exception e){
System.err.println(e);
onStopButtonClick();
}
}
The run command method makes a new process builder in cmd and executes the command I pass into it, using threading it goes through the output of the cmd line. I make a new thread that runs through the lines until I press the stop button to make the thread running variable false.
onStopButtonClick Method
#FXML
protected void onStopButtonClick(){
threadRunning = false;
p.destroy();
loggingStatus.setText("File has been saved!");
startButton.setDisable(false);
stopButton.setDisable(true);
spinner.setOpacity(0);
}
Stopping
When the stop button is pressed this code gets executed, ending the thread and destroying the process, along with some other screen changes.
The issue I'm having is that everything works exactly as intended, except the fact that when I press stop, the logging continues, and the logging ONLY stops when I close the application which is less than ideal functionality. I am confident threading is working to some extent since some of the code is being executed in the onStopButtonClick method, but the logging still continues despite that.
If anything it seems like I wrote the threading wrong, not sure where I messed up or if this is even achievable at all.
Appreciate any help, Thanks. :)
Am trying to get a series of commands on git bash one after the other. I can open the terminal through the code but after that wasn't successful with entering anything. For instance this is the code I tried
String [] args = new String[] {"C:\\Program Files\\Git\\git-bash.exe"};
String something="hi how are you doing";
try {
ProcessBuilder p = new ProcessBuilder();
var proc = p.command(args).start();
var w = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
w.write(something);
} catch (IOException ioException){
System.out.println(ioException);
}
Please let know how to be able to do enter a series of commands into git bash through the code.
The problem is that the command git-bash.exe opens the terminal window but the window's input is still the keyboard, so trying to write to the OutputStream that is returned by method getOutputStream(), in class Process does nothing. Refer to this question.
As an alternative, I suggest using using ProcessBuilder to execute a series of individual git commands. When you do that, your java code gets the command output.
Here is a simple example that displays the git version.
import java.io.IOException;
public class ProcBldT4 {
public static void main(String[] args) {
// C:\Program Files\Git\git-bash.exe
// C:\Program Files\Git\cmd\git.exe
ProcessBuilder pb = new ProcessBuilder("C:\\Program Files\\Git\\cmd\\git.exe", "--version");
pb.inheritIO();
try {
Process proc = pb.start();
int exitStatus = proc.waitFor();
System.out.println(exitStatus);
}
catch (IOException | InterruptedException x) {
x.printStackTrace();
}
}
}
When you run the above code, the git version details will be written to System.out.
Also, if the git command fails, the error details are written to System.err.
You need to repeat the code above for each, individual git command that you need to issue.
So essentially, I am trying to run the command "/dir/command -arg" to change the LED color on a USB device in Java. I am using Ubuntu 10.04. When I run the command from the terminal, it works just fine.
However, I tried every iteration of Runtime.exec() that I could find and none of them seem to work. I then created a script with the following contents:
#!/bin/bash
echo "hello"
/dir/command -arg
when I run this from a terminal it works just fine. However when I run
#Override
public void run() {
String[] lookupCmd = {"/bin/sh","-c", "sh /dir/script.sh"};
try {
Runtime runtime = Runtime.getRuntime();
Process lookupProc = runtime.exec(lookupCmd);
lookupProc.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(lookupProc.getInputStream()));
String line = reader.readLine();
while (line != null) {
id.add(line);
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e) {
System.err.println(e);
}
}
"hello" print but nothing else. There is no error.
My other command should not yield any output, but simply change the color of an LED. However when I run it with the same command but a different arg which yields an ouput, it still only prints "hello".
I also made sure that my user has permissions to the /dev folder with the usb device.
I wasn't running the error stream, so I've added that.
After that I realized I was missing an environment variable, so added:
String[] envar = {"VAR=path"}
and called:
runtime.exec(lookupCmd, envar);
Works great now.
I am wondering is there any way to execute following shell script, which waits for user input using java's Runtime class?
#!/bin/bash
echo "Please enter your name:"
read name
echo "Welcome $name"
I am using following java code to do this task but it just shows blank console.
public class TestShellScript {
public static void main(String[] args) {
File wd = new File("/mnt/client/");
System.out.println("Working Directory: " +wd);
Process proc = null;
try {
proc = Runtime.getRuntime().exec("sudo ./test.sh", null, wd);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thing is when I execute above program, I believed it will execute a shell script and that shell script will wait for user input, but it just prints current directory and then exits. Is there any way to do this or it is not possible at all in java?
Thanks in advance
The reason it prints the current dir and exits is because your java app exits. You need to add a (threaded) listener to the input and error streams of your created process, and you'll probably want to add a printStream to the process's output stream
example:
proc = Runtime.getRuntime().exec(cmds);
PrintStream pw = new PrintStream(proc.getOutputStream());
FetcherListener fl = new FetcherListener() {
#Override
public void fetchedMore(byte[] buf, int start, int end) {
textOut.println(new String(buf, start, end - start));
}
#Override
public void fetchedAll(byte[] buf) {
}
};
IOUtils.loadDataASync(proc.getInputStream(), fl);
IOUtils.loadDataASync(proc.getErrorStream(), fl);
String home = System.getProperty("user.home");
//System.out.println("home: " + home);
String profile = IOUtils.loadTextFile(new File(home + "/.profile"));
pw.println(profile);
pw.flush();
To run this, you will need to download my sourceforge project: http://tus.sourceforge.net/ but hopefully the code snippet is instructive enough that you can just adapt to J2SE and whatever else you are using.
If you use a Java ProcessBuilder you should be able to get the Input, Error and Output streams of the Process you create.
These streams can be used to get information coming out of the process (like prompts for input) but they can also be written to to put information into the process directly too. For instance:
InputStream stdout = process.getInputStream ();
BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
String line;
while(true){
line = reader.readLine();
//...
That'll get you the output from the process directly. I've not done it myself, but I'm pretty sure that process.getOutputStream() gives you something that can be written to directly to send input to the process.
The problem with running interactive programs, such as sudo, from Runtime.exec is that it attaches their stdin and stdout to pipes rather than the console device they need. You can make it work by redirecting the input and output to /dev/tty.
You can achieve the same behaviour using the new ProcessBuilder class, setting up the redirection using ProcessBuilder.Redirect.INHERIT.
Note sure at all you can send input to your script from Java. However I very strongly recommend to have a look at Commons Exec if you are to execute external scripts from Java:
Commons Exec homepage
Commons Exec API
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