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"
);
Related
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.
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());
NOTE: Path of python.exe has already been set
I am trying to create a Java program that passes the variable args (or any other variable) to a Python script.
import java.io.*;
public class PythonCallTest{
public static void main (String[] args){
String s = null;
Runtime r = Runtime.getRuntime();
try{
Process p = r.exec("cmd /c python ps.py+",args);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null){
System.out.println(s);
}
while ((s = stdError.readLine()) != null){
System.out.println(s);
}
System.exit(0);
}
catch(IOException ioe){
ioe.printStackTrace();
System.exit(-1);
}
}
}
The program compiles but when I run it with
java PythonCallTest sender-ip=10.10.10.10
I get the error
'python' is not recognized as an internal or external command, operable program or batch file.
How do I properly concatenate the string in r.exec("cmd /c python ps.py+",args)
EDIT
If I execute the following
Process p = r.exec("cmd /c python ps.py sender-ip=10.251.22.105");
Then the program works. The path for python.exe has already been set. I just need to know how to add args to r.exec, i.e how to concatenate cmd /c python ps.py with args
You are passing args as the second argument of Runtime.exec(...).
This overrides the default (inherited) environment of the new process to be useless, and hence the Path variable no longer contains the path to python.exe.
You need to use this version of Runtime.exec(...):
public Process exec(String[] cmdarray);
Which you would do so like this:
public static void main(String[] args) {
...
List<String> process_args = new ArrayList<String>(Arrays.asList("cmd", "/c", "python", "ps.py"));
process_args.addAll(Arrays.asList(args));
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(process_args.toArray(new String[] {}));
...
} catch (IOException e) {
...
}
}
hi im trying to do a program that will be able to access command prompt and be able to start solr's start.jar file so my search program could work..the problem is when im using the codes in eclipse, the program runs smoothly but when i transfered my program in netbeans it says that it cannot access the jar file.it doesnt give me any stack trace error that is why i dont know what is wrong..here is my code
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CmdTest {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"D:\\Downloads\\solr-4.2.1\\solr-4.2.1\\example\" && java -jar start.jar");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
the error is just plainly like this : Error:Unable to access jarfile start.jar
I can think of a few things to start with...
Each parameter you past to the ProcessBuilder is expected to be a separate argument for the command to be executed. Fine, I'm not 100% if the command you've constructed will work, but it just looks like a mess to me.
Instead, if you want to change the location that the command is executed in, why not just use the directory method of ProcessBuilder, which will change the execution context to the specified location when the command is executed...
public class CmdTest {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder("java.exe", "-jar", "start.jar");
builder.directory(new File("D:\\Downloads\\solr-4.2.1\\solr-4.2.1\\example"));
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
}
}
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