You can run application using java by passing command to exec method of java.lang.Runtime object. Here is a sample code for opening calculator in java on Windows or Linux(Ubuntu).
save the below code with name RunApplication.java
save the below code with name RunApplication.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package com.trickyjava.general; public class RunApplication { public static void main(String[] args) { try { String command = getCalculatorCommand(); if (null == command) { throw new Exception("Command Not found"); } System.out.println("Opening Calculator"); Runtime runTime = Runtime.getRuntime(); Process process = runTime.exec(command); Thread.sleep(5000); System.out.println("Closing Calculator"); process.destroy(); } catch (Exception e) { e.printStackTrace(); } } public static String getCalculatorCommand() { String OS = System.getProperty("os.name").toLowerCase(); if (OS.startsWith("windows")) { return "calc"; } else if (OS.startsWith("linux")) { return "gcalctool"; } return null; } } |
its method getCalculatorCommand() is used to find-out the Operating Specific command. We have made compatible for Windows and Linux.
Output of the following code: