I want to execute below command from java program .
java -jar jarfile.jar -dir C:/MyDirectory -out C:/MyDirectory/example.html
I tried following , but its opening cmd prompt , but it not executing next command
Runtime rt = Runtime.getRuntime();
try {
rt.exec(new String[] { "cmd.exe", "/c", "start" , "java -jar exampleJar.jar -dir C:\\MyDirectory -out C:\\MyDirectory\\exampleHtml.html" });
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am using the following piece of code and its working perfect,ProcessBuilder is used to create operating system processes and each instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. To create new subprocesses with the same instance start() method can be called repeatedly.
public void execute(String[] code){
try{
ProcessBuilder pb=new ProcessBuilder(code);
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while(inStreamReader.readLine() != null){
System.out.println(inStreamReader.readLine());
}
} catch (IOException e) {
System.out.println(e.toString());
e.printStackTrace();
log.error(e.getMessage());
}
}
Related
I want to run :
export JAVA_HOME=/home/sofiane/install/jdk1.8.0_121/
export ANDROID_HOME=/home/sofiane/Android/Sdk/
npm run android
from a program java using commande line.
Thank you.
Java class
public static void executeCommands() throws IOException {
ProcessBuilder pb = new ProcessBuilder("bash", "./shell.sh");
pb.inheritIO();
Process process = pb.start();
try {
process.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
shell.sh
#!/bin/bash
export JAVA_HOME=/home/sofiane/install/jdk1.8.0_121/
export ANDROID_HOME=/home/sofiane/Android/Sdk/
cd /home/sofiane/work/MyAcceleo/fichier/pfe
npm run android
Result :
Please know that stanford is not exe. it is a folder consists many programs
I open the cmd.exe by using following statement:
public static void runStanfordCMD() throws IOException{
List<String> cmds = Arrays.asList("cmd.exe", "/C", "start", "java", "-mx4g", "-cp", "*", "edu.stanford.nlp.pipeline.StanfordCoreNLPServer");
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.directory(new File("D:/Desktop/stanford-corenlp-full-2015-12-09"));
Process proc = builder.start();
}
so how to close the cmd.exe after I finished some process?
by using ProcessBuilder or Runtime?
If using ProcessBuilder how to write the statement according to my case?
how to write the statement to the Runtime according to my case?
public static void closeStanfordCMD() throws IOException{
try {
Runtime.getRuntime().exec("command.exe /C" + "Your command"); // how to write the statement?
} catch (Exception e) {
e.printStackTrace();
}
}
The method
Runtime.getRuntime().exec
returns an object of Process.
Process has a method destroy() which kills the process you're running.
So what you need is to store the Process object returned by the exec method and call destroy() on it when you want to kill the process.
Also you can call waitFor() method to wait for the process to stop (Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated).
To make it clear, try this code (or modify for your needs):
try {
Process p = Runtime.getRuntime().exec("java -mx4g -cp * D:/Desktop/stanford-corenlp-full-2015-12-09/edu.stanford.nlp.pipeline.StanfordCoreNLPServer");
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
// how to write the statement?
if you want to close command prompt:
Runtime.getRuntime().exec("taskkill /IM " + "cmd.exe");
if you want to close stanford.exe:
Runtime.getRuntime().exec("taskkill /IM " + "stanford.exe");
I have the following test code:
public class TestProcessBuilder {
public static void main(String args[]) {
String imageLocation = "/home/john/image";
String installCommand = "java -jar install.jar -install /home/john/install.properties";
ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File(imageLocation));
pb.command(Arrays.asList(installCommand.split("\\+s")));
try {
pb.start();
} catch(Exception e) {
e.printStackTrace();
System.out.println("Failed to run command");
}
}
This gives me an error:
Cannot run program "java -jar install.jar -install /home/john/install.properties" (in directory "/home/john/"): error=2, No such file or directory
Do I have to create a separate list and then manually add each tokenized item to it. I thought this should work...
You should make sure that path to your java folder is exported. You can then use something similar to this:
public static void main(String[] args) {
String command = "java";
String parameters = "-jar install.jar -install /home/john/install.properties";
ProcessBuilder pb = new ProcessBuilder(command, parameters);
try {
pb.start();
} catch (IOException e) {
e.printStackTrace();
}
}
Depends of your need, but you could use also this if you want to pass whole command in one string:
try {
Runtime.getRuntime().exec("java -jar install.jar -install /home/john/install.properties");
} catch (IOException e) {
e.printStackTrace();
}
I'm trying to run a simple command from console using this
public void execute(File file, String... command){
Process p = null;
ProcessBuilder builder = new ProcessBuilder("ls");
builder.directory(file.getAbsoluteFile());
builder.redirectErrorStream(true);
try {
p = builder.start();
} catch (IOException e) {
LOGGER.error("", e);
}
}
but it kept saying that I cant run ls, permission denied. Is there any missing step here?
Thanks
You should use pass the commands and the flags to the constructor of the ProcessBuilder separately (as per the docs):
public void execute(File file, String... command) {
ProcessBuilder builder = new ProcessBuilder("ls", "-l");
builder.directory(file.getAbsoluteFile());
builder.redirectErrorStream(true);
try {
Process p = builder.start();
} catch (IOException e) {
LOGGER.error("", e);
}
}
It seems you want to execute command, though. To do this, you can pass command to ProcessBuilder's constructor.
public void execute(File file, String... command) {
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(file.getAbsoluteFile());
builder.redirectErrorStream(true);
try {
Process p = builder.start();
} catch (IOException e) {
LOGGER.error("", e);
}
}
Here's the ideone to the working code
You'll notice that when I run it with "ls -l", there's a problem executing the command. This is because the first argument is treated as the command to be executed and the remaining arguments are treated as flags.
To change permissions of bash commands in EC2 instances, execute
chmod u+x /home/admin/ec2-api-tools-*/bin/*
This depends on a couple of things:
1) The user that runs java (your process will be ran as that user)
2) The directory where your JAR or class resides.
Also make sure that your account has proper permissions if the java user is not the same as the user you are logged in as.
ProcessBuilder builder = new ProcessBuilder("ls -l");
There is no process named "ls -l". You want to use the process named "ls" with the arguments "-l", for that you need:
ProcessBuilder builder = new ProcessBuilder("ls", "-l");
I have a sample Java application that I registered as a service using Procrun. I am trying to execute Batch file from my application
public class Service {
public static void main(String args[]) throws IOException, InterruptedException {
if(args.length>0){
if(args[0].equals("start")){
ProcessBuilder builder = new
ProcessBuilder("cmd","/c","start","Start.bat");
builder.start();
}else if(args[0].equals("shutdown")){
ProcessBuilder builder = new
ProcessBuilder("cmd","/c","start","Stop.bat");
builder.start();
}
}
}
}
When I am starting the service, it gets started successfully but it does not launch batch file on my Windows 7.
Contents of Batch files are given below
Start.bat
#echo off
echo I am started
pause
Please let me know what am I missing here
Have you tried following
Runtime.getRuntime().exec("cmd /c start Start.bat");
To execute batch file from java application, try this piece of code:
// "D://bin/" is the location of my .bat
File dir = new File("D:/bin/");
try {
// sign.bat if my actual file.
Runtime.getRuntime().exec("cmd.exe /c sign.bat", null, dir);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}