Robot
Java awt Robot class is used to generate input events. It is used for tests automation and app that need mouse and keyboard control. Use robot to move mouse 1 pixel.
import java.awt.MouseInfo;
import java.awt.Robot;
import java.awt.Point;
class RobotApp {
public static void main(String[] args) throws AWTException {
Robot robot = new Robot();
while(true) {
robot.delay(1000 * 3);
Point pos = MouseInfo.getPointerInfo().getLocation();
robot.mouseMove(pos.x + 1, pos.y + 1);
System.out.println("Mouse moved");
}
}
}
Switch focus ALT+TAB between open applications.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
class RobotApp {
public static void main(String[] args) throws AWTException {
Robot robot = new Robot();
while(true) {
robot.delay(1000 * 5);
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_TAB);
}
}
}
EXEC
Open application using exec() runtime method.
import java.io.IOException;
class RobotApp {
public static void main(String[] args) throws IOException {
Runtime.getRuntime().exec(
new String[] { "chromium-browser", "http://google.com/" }
);
Runtime.getRuntime().exec(
new String[] {
"google-chrome",
"https://www.google.com/search?q=java+runtime+open+app"
}
);
}
}
SHELL
Open the terminal and run a command.
/**
* Usage of Runtime.exec() is discourage (oracle docs)
* Use ProcessBuilder insteed
*/
import java.io.IOException;
class ExecTest {
public static void main(String[] args) throws IOException {
new ProcessBuilder(new String[] {
"/bin/sh", "-c",
"gnome-terminal --command=\"bash -c 'java -version; $SHELL'\""
}).start();
}
}
Open the terminal and run jar archive.
import java.io.IOException;
class ExecTest {
public static void main(String[] args) throws IOException {
new ProcessBuilder(new String[] {
"/bin/sh", "-c",
"gnome-terminal --command=\"" +
"bash -c " +
"'cd /var/www/java/projects/Maven/test/ && " +
"java -jar test.jar; $SHELL'\""
}).start();
}
}
Run shell command in background from java program.
import java.io.IOException;
class ExecTest {
public static void main(String[] args) throws IOException {
new ProcessBuilder(new String[] {
"/bin/sh", "-c",
"cd /var/www/java/projects/Maven/test/ && " +
"java -Dname=myapp -jar test.jar"
}).start();
// pkill -9 -f myapp
}
}
BACKGROUND
The & symbol runs the program in background. The nohup runs the program even if you close the terminal.
#!/bin/sh
nohup java -jar /web/server.jar &
Show all java processes.
ps aux | grep java
# a = show processes for all users
# u = display the process's user/owner
# x = also show processes not attached to a terminal
Use kill if you want to stop a process.
pkill -9 java
# kill all java processes
kill -9 PID
# kill process by id
pkill -9 -f myapp
# kill process by app name
Last update: 182 days ago