How to execute command with parameters? - java

How am I to execute a command in Java with parameters?
I've tried
Process p = Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php -m 2"});
which doesn't work.
String[] options = new String[]{"option1", "option2"};
Runtime.getRuntime().exec("command", options);
This doesn't work as well, because the m parameter is not specified.

See if this works (sorry can't test it right now)
Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php", "-m", "2"});

Use ProcessBuilder instead of Runtime#exec().
ProcessBuilder pb = new ProcessBuilder("php", "/var/www/script.php", "-m 2");
Process p = pb.start();

The following should work fine.
Process p = Runtime.getRuntime().exec("php /var/www/script.php -m 2");

Below is java code for executing python script with java.
ProcessBuilder:
First argument is path to virtual environment
Second argument is path to python file
Third argument is any argumrnt you want to pass to python script
public class JavaCode {
public static void main(String[] args) throws IOException {
String lines = null;
ProcessBuilder builder = new ProcessBuilder("/home/env-scrapping/bin/python",
"/home/Scrapping/script.py", "arg1");
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((lines = reader.readLine())!=null) {
System.out.println("Line: " + lines);
}
}
}
First is virtual environment path

Related

Using ProcessBuilder to compile multiple java files throws File not found error

I have simple java program for compiling java classes.
I created a JAR of this program and when I run it on Ubuntu I pass to the jar the path of folder with java files.
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
compile(args[0]);
}
//pathToFiles - is a value from command line arguments
private static void compile(String pathToFiles) throws IOException, InterruptedException {
List<String> cmdList = new ArrayList<>();
cmdList.add("javac");
cmdList.add(pathToFiles);
System.out.println("cmd: "+cmdList);
ProcessBuilder pb = new ProcessBuilder(cmdList);
Process process = pb.start();
int exitValue = process.waitFor();
if (exitValue != 0) {
generateCompileException(process);
}
}
//method just generates error message if there was an error
private static void generateCompileException(Process process){
StringBuilder response = new StringBuilder();
try (final BufferedReader b = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
String line;
if ((line = b.readLine()) != null)
response.append(line);
} catch (final IOException e) {
e.printStackTrace();
}
throw new RuntimeException(response.toString());
}
}
When I pass path containing single java file it works:
java -jar co-1.jar /home/admin/test2/Calculator.java
But I want to compile multiple files. When I pass path containing multiple files I get error: file not found.
java -jar co-1.jar '/home/admin/test2/*.java'
PS: If I run a javac command manually with multiple files, it will work:
###################################
UPDATE:
I've added bash command to ProcessBuilder:
private static void compile(String pathToFiles) throws IOException, InterruptedException {
List<String> cmdList = new ArrayList<>();
cmdList.add("bash");
cmdList.add("-c");
cmdList.add("javac");
cmdList.add(pathToFiles);
System.out.println("Processor builder command: "+cmdList);
ProcessBuilder pb = new ProcessBuilder(cmdList);
Process process = pb.start();
int exitValue = process.waitFor();
if (exitValue != 0) {
System.out.println("Finished with error. Exit value: "+exitValue);
generateCompileException(process);
}
}
But process withished with error code 2 with empty response from ProcessBuilder.
PS: RuntimeException was thrown by this line: throw new RuntimeException(response.toString());
ProcessBuilder will not evaluate wildcards, as that is a feature of your terminal (such as bash). If you want wildcard to be expanded you need to run bash inside ProcessBuilder command, such as:
String commandContainingWildcard = "javac /blah/*.java";
ProcessBuilder pb = new ProcessBuilder("bash", "-c", commandContainingWildcard);
... // start() etc
For the above to work you need to have "bash" or whatever shell you use in your path, otherwise you will need to use full path to bash (such as "/bin/bash").
The third argument for command to compile must exactly match what works inside your terminal and must be the entire value not "javac" followed by wildcard. Remove single quotes around *.java (so that ProcessBuilder is provided with three command line parameters, not four or more).
However I suggest that ProcessBuilder with bash isn't the best way to do this work. You could try Java compiler tool interface, and get rid of wildcard by easy use of Files.find(dir, 1, (p,a) -> p.getFileName().toString().endsWith(".java")) to scan for all java files and join the paths explicitly for compilation.
UPDATE
Having now resolved your problem you may now find that the javac process fails / freezes due the incorrect way you read the stderr stream - this needs to happen at same time as stdout and before process.waitFor(). An easy fix is to consume stdout+stderr together:
ProcessBuilder pb = new ProcessBuilder(cmdList);
pb.redirectErrorStream(true);
Process process = pb.start();
ByteArrayOutputStream response = new ByteArrayOutputStream();
process.getInputStream().transferTo(response);
int exitValue = process.waitFor();
if (exitValue != 0) {
System.out.println("Finished with error. Exit value: "+exitValue);
throw new RuntimeException(new String(response.toByteArray()));
}
Remove quotes and use the command as below.
java -cp co-1.jar:/home/admin/test2/* Main.class <args>
See also
https://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
PS: Unix uses :(colon) as delimiter and windows uses ;(semi-colon) delimiter to separate multiple paths.

Trying to run an application from Java

I need to run the "VBoxManage vms list command" to see the virtual machines installed on a computer from a Java application.
The following code works correctly but only if I use the Runtime class but I would like to know why it fails if I use ProcessBuilder.
The code is the following:
public static void main(String[] args) throws IOException {
String folder= "c:/Program files/Oracle/VirtualBox";
List<String> comand = Arrays.asList(
"VBoxManage",
"list",
"vms"
);
ProcessBuilder pb = new ProcessBuilder()
.directory(new File(folder))
.command(comand);
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while((line=br.readLine()) != null){
System.out.println(line);
}
}
This works fine if I use the Runtime class with this code:
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("c:/Program files/Oracle/VirtualBox/vboxmanage list vms");
Thank you.
Try using the full path of the executable, like you do when using Runtime.exec
List<String> comand = Arrays.asList(
"c:/Program files/Oracle/VirtualBox/VBoxManage",
"list",
"vms"
);

How can I run a shell script, written in Bash on Ubuntu, from Java in a Windows 10 environment?

How can I run a shell script, written in Bash on Ubuntu, from Java in a Windows 10 environment?
I'm trying to use this code but it is not running nor executing the script.
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
ProcessBuilder builder = new ProcessBuilder(
"bash.exe", "/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh");
Process p = builder.start();
BufferedReader r = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line != null) { System.out.print(line);}
else{break;}
}
}
First of all: did you try to execute this command from command line? If you did and it worked it means that problem is not with bash on windows but with your java program.
If you cannot execute it from command line then fix this problem first
I cannot test my program because I use Ubuntu but can advice you to try smth like this: (wait until program is over)
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(
"bash.exe", "/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh");
Process p = builder.start();
/* waitFor() method stops current thread until this process is over */
p.waitFor();
// I think that scanner is a nicer way of parsing output
Scanner scanner = new Scanner(p.getInputStream());
while (scanner.hasNextLine()) {
// you do not have to create `line` outside the loop
// it does not change performance of a program
String line = scanner.nextLine();
System.out.println(line);
}
}
}
If you are trying to run a script using Java in a Windows environment, I would suggested executing it differently.
I have adapted you code from a precious question asked here :
How to run Unix shell script from Java code?
Also, this question will help you with your question:
Unable to read InputStream from Java Process (Runtime.getRuntime().exec() or ProcessBuilder)
public static void main(String[] args) throws IOException {
Process proc = Runtime.getRuntime().exec(
"/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh");
BufferedReader read = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while (read.ready())
{
System.out.println(read.readLine());
}
}
I believe this is what you are looking for. I believe that your Java code was a little off and these edits should help you. After you build the java executable, you could be able to run it via Window's Command Prompt.

Process builder won't find my file

I am trying to compile a java program using the ProcessBuilder but everytime i see this error being present on the console even though the file is present at that path.
ERROR
java.io.IOException: Cannot run program "javac
/Users/foo/Desktop/online-compiler/user1455523443383/Main.java":
error=2, No such file or directory
#Override
public ProgramResult executeProgram(File program) throws IOException {
String parent = program.getParentFile().getParentFile().getAbsolutePath();
String[] commands = new String[]{
"javac "+program.getAbsolutePath(),
// "cd "+parent,
// "java -cp "+parent+" "+PACKAGE_NAME+"."+MAIN_CLASS
};
ProcessBuilder builder = new ProcessBuilder(commands);
builder.redirectErrorStream(true);
Process executorProcess = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(executorProcess.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while((line = reader.readLine())!=null) {
sb.append(line);
}
reader.close();
ProgramResult result = new ProgramResult();
result.setOutput(sb.toString());
return result;
}
Some more information
Javac is on the path, as running it(without the file) via ProcessBuilder is printing the help options.
OS : MACOSX
Conclusions from this questions are
1) ProcessBuilder needs every argument to the command as a separate index , like to execute "javac filename.java" you write this
new String[] {"javac" , "filename.java"}
2) To execute multiple commands you should be using the following trick
new String[]{
"/bin/bash",
"-c",
"javac "+
program.getAbsolutePath()+
" &&" +
" java -cp " +
parent +
" "+ PACKAGE_NAME+"."+MAIN_CLASS,
}
A big thanks to #kucing_terbang for really digging in this problem with me to solve it.
AFAIK, if you want to put an argument into the ProcessBuilder, you should put in into another index of the array.
So, try change the command variable into something like this and try again.
String[] commands = new String[]{"javac", program.getAbsolutePath()};
If you want to compile a Java class, better use JavaCompiler acquired from ToolProvider.getSystemJavaCompiler();
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
javaCompiler.run(null, null, null, program.getAbsolutePath());

how to launch a shell script in a new gnome terminal, from a java program

I'm trying to run a shell script (say myscript.sh) from a java program.
when i run the script from terminal, like this :
./myscript.sh
it works fine.
But when i call it from the java program, with the following code :
try
{
ProcessBuilder pb = new ProcessBuilder("/bin/bash","./myScript.sh",someParam);
pb.environment().put("PATH", "OtherPath");
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line ;
while((line = br.readLine()) != null)
System.out.println(line);
int exitVal = p.waitFor();
}catch(Exception e)
{ e.printStackTrace(); }
}
It doesnt goes the same way.
Several shell commands (like sed, awk and similar commands) get skipped and donot give any output at all.
Question : Is there some way to launch this script in a new terminal using java.
PS : i've found that "gnome-terminal" command launches a new terminal in shell,
But, i'm unable to figure out, how to use the same in a java code.
i'm quite new to using shell scripting. Please help
Thanks in advance
In java:
import java.lang.Runtime;
class CLI {
public static void main(String args[]) {
String command[] = {"/bin/sh", "-c",
"gnome-terminal --execute ./myscript.sh"};
Runtime rt = Runtime.getRuntime();
try {
rt.exec(command);
} catch(Exception ex) {
// handle ex
}
}
}
And the contents of the script are:
#!/bin/bash
echo 'hello!'
bash
Notes:
You'll do this in a background thread or a worker
The last command, in the shell script, is bash; otherwise execution completes and the terminal is closed.
The shell script is located in the same path as the calling Java class.
Don't overrwrite your entire PATH...
pb.environment().put("PATH", "OtherPath"); // This drops the existing PATH... ouch.
Try this instead
pb.environment().put("PATH", "OtherPath:" + pb.environment().get("PATH"));
Or, use the full directories to your commands in your script file.
You must set your shell script file as executable first and then add the below code,
shellScriptFile.setExecutable(true);
//Running sh file
Process exec = Runtime.getRuntime().exec(PATH_OF_PARENT_FOLDER_OF_SHELL_SCRIPT_FILE+File.separator+shellScriptFile.getName());
byte []buf = new byte[300];
InputStream errorStream = exec.getErrorStream();
errorStream.read(buf);
logger.debug(new String(buf));
int waitFor = exec.waitFor();
if(waitFor==0) {
System.out.println("Shell script executed properly");
}
This worked for me on Ubuntu and Java 8
Process pr =new ProcessBuilder("gnome-terminal", "-e",
"./progrm").directory(new File("/directory/for/the/program/to/be/executed/from")).start();
The previous code creates a new terminal in a specificied directory and executes a command
script.sh Must have executable permissions
public class ShellFileInNewTerminalFromJava {
public static void main(String[] arg) {
try{
Process pr =new ProcessBuilder("gnome-terminal", "-e", "pathToScript/script.sh").start();
}catch(Exception e){
e.printStackTrace();
}
}
}

Categories