I am trying to run a .jar from within my Java program. I am using ProcessBuilder to do so, but it is not working correctly.
I am wondering if I am missing something.
This is what I currently have that is trying to run the .jar
ProcessBuilder pb = new ProcessBuilder("java", "-jar", System.getProperty("user.home") + "/JARFile/JARFile.jar");
Process p = pb.start();
I have the directory correct, so I am not positive why this is not working properly.
Do I have something wrong with my parameters in the new ProcessBuilder?
1) in third argument set full path to file:
ProcessBuilder pb = new ProcessBuilder("java", "-jar",
"/home/meiskalt7/Documents/runJar-55056616-1.0-SNAPSHOT.jar");
Result will be look like this:
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("java", "-jar",
"/home/meiskalt7/Documents/runJar-55056616-1.0-SNAPSHOT.jar");
Process p = pb.start();
InputStream in = p.getInputStream();
System.out.println(new BufferedReader(new InputStreamReader(in))
.lines().collect(Collectors.joining("\n")));
}
and in console you will see result of execution
2) If everything will be good then you must check your system property with
System.out.println(System.getProperty("user.home"))
and if path looks like path in first step then you must compare path with equals operator:
System.out.println((System.getProperty("user.home") + "/JARFile/JARFile.jar")
.equals([YOUR FULL PATH]))
Maybe your problem with symbols of another language in path
2*) if something go wrong then you can check error of process execution in error stream of your process:
InputStream err = p.getErrorStream();
System.out.println(new BufferedReader(new InputStreamReader(err))
.lines().collect(Collectors.joining("\n")));
Related
I adopted the code from one of the similar questions:
Process p = null;
ProcessBuilder pb = new ProcessBuilder("scr.sh");
pb.directory(new File("/Users/alex/"));
p = pb.start();
Thread.sleep(TimeConst.SECOND);
And run this code from public static main(), I did place scr.sh file under alex folder but receive the exception: Caused by: java.io.IOException: error=2, No such file or directory
What's wrong with my code?
I removed a line that specified a working directory and replace file name with a absolute path instead and then it worked.
In order to receive echo messages I had to read from my stdin (?):
final Scanner in = new Scanner(p.getInputStream());
new Thread(() -> {
while (in.hasNextLine())
System.out.println(in.nextLine());
}).start();
I have a project that uses ProcessBuilder to capture the output of the command "java -jar someJar.jar -argument", but have now moved the jar's source files to a separate package; somepackage. The package has a main function, so I would like to create a ProcessBuilder that captures the output of that process, as if it were a different Thread.
Is this possible, or will I have to completely re-write the code to allow it to use the source files instead of the binary?
If I'm assuming right, the package has main function and we are trying to get output of the main method that executes with java -jar processbuilder command.
ProcessBuilder pb = new ProcessBuilder(your java -jar command);
Process process = pb .start();
process.waitFor();
BufferedInputStream in = new BufferedInputStream(process.getInputStream());
byte[] contents = new byte[1024];
int jwtOytputBytesRead = 0;
String Output = "";
while ((jwtOytputBytesRead = in.read(contents)) != -1) {
Output += new String(contents, 0, jwtOytputBytesRead);
}
System.out.println(Output);
Try this link as well to specify the main the class
Run class in Jar file
I need to start a server using bash, so I had created an UNIX shell , but I am not able to execute it with Java from Eclipse.
I tried the following code which doesn't work :
Process proc = Runtime.getRuntime().exec(./startServer);
Here is content of the startServer file :
#!/bin/bash
cd /Users/sujitsoni/Documents/bet/client
npm start
You can try the following two options.
Option 1
Process proc = Runtime.getRuntime().exec("/bin/bash", "-c", "<Abosulte Path>/startServer");
Option 2
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "<Absolute Path>/startServer");
pb.directory(new File("<Absolute Path>"));
Process proc = pb.start();
A couple Of things can go wrong:
The path to the file you have given might be wrong for eclipse it can take relative path but from the command line, it will take the absolute path.
error=13, Permission denied - If the script file doesn't have required permissions. In your scenario, that might not the case as you are not getting any error.
At last, you are executing the script by java program so the output of your script will not be printed out. In your scenario, this might be the case. You need to capture the output of script from BufferedReade and print it. ( In your case server might have started but you are not seeing the logs/output of the script.
See the code sample below for printing output.
public static void main(String[] args) throws IOException, InterruptedException {
Process proc = Runtime.getRuntime().exec("./startServer");
proc.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output);
}
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
i have a .jar file, which I can run on the command line:
java -jar myFile.jar argument1
I want to save the output of this .jar as a String variable inside another java program.
How can I do it?
I tried including myFile.jar as a reference in my program, and doing myFile.main(new String{"argument1"}) in my program. But this just prints the results to console, I can't use the results in my program.
Hope this is not too confusing.
I
Running Jar file require you to have the jar file included in your class path. This can be done at run time using URLClassLoader. Simply construct a URLClassLoader with the jar as one of the URL. Then call its forClass(...) if you know the class name (full name of course). Or inspect the manifest file using its 'findResources(String name)'.
Once you get the class, you can use reflection to get its static method main.
Seeing your question again, you know the class name, so if you are sure the jar file in already in the class path, then you can just call it as you tried.
II
To capture the output, you can call System.setOut(PrintStream out) and System.setErrPrintStream out) to change the print stream. You can pass the printstream that you create. Like this:
ByteArrayOutputStream BAOS = new ByteArrayOutputStream();
PrintStream MyOut = new PrintStream(BAOS);
System.setOut(MyOut);
// Do something to have something printed out.
...
String TheCaptured = new String(BAOS.toByteArray());
Hope this helps.
If you can't include the other jar,
you can use something like that
Runtime re = Runtime.getRuntime();
BufferedReader output;
try{
cmd = re.exec("java -jar MyFile.jar" + argument);
output = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
} catch (IOException ioe){
ioe.printStackTrace();
}
String resultOutput = output.readLine();
I know my code isn't perfect like the catching exception, etc but I think this could give you a good idea.
Being a Jar file, you can add it to your class path and call the functionality of the program your self. You might need to know more about the logic behind the Jar to use it without having it output the information..
I believe what you are looking for is how to shell execute the Jar archive. An example can be found here.
Take a look at ProcessBuilder:
http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html
It effectively creates an operating system process which you can then capture the output from using:
process.getInputStream().
The line:
processbuilder.redirectErrorStream(true)
will merge the output stream and the error stream in the following example:
e.g.
public class ProcessBuilderExample {
public ProcessBuilderExample() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "gscale.jar");
pb.redirectErrorStream(true);
pb.directory(new File("F:\\Documents and Settings\\Administrator\\Desktop"));
System.out.println("Directory: " + pb.directory().getAbsolutePath());
Process p = pb.start();
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println( line ); // Or just ignore it
}
p.waitFor();
}
}