I'm trying to execute julia.exe in Java.
Here is the code:
Process pTest = Runtime.getRuntime().exec("C:/Program Files/Julia-0.4.1/bin/julia.exe");
When I run it, nothing happens.
However, if I try another executable file, it works well. For example:
Process pTest = Runtime.getRuntime().exec("C:/Program Files/anotherProgram/program.exe");
program.exe will run just as expected.
julia.exe is a little special.
If I run it on command prompt, it will execute on the command prompt. In other words, it won't pop up its own window.
I've done a test:
#julia script, it's path: C:/Users/Thomas/Julia/test.jl
function test1()
println("it's test1")
end
test1()
I execute this command on the command prompt:
C:\>C:/Program Files/Julia-0.4.1/bin/julia.exe C:/Users/Thomas/Julia/test.jl
then I will get it's test1 on the command prompt.
What I need is to execute C:/Program Files/Julia-0.4.1/bin/julia.exe C:/Users/Thomas/Julia/test.jl in my java project and get it's test1 on the console of eclipse.
Here is my java project:
public class Main {
public static void main(String[] args){
try {
String[] params = {"C:/Program Files/Julia-0.4.1/bin/julia.exe", "C:/Users/Thomas/Julia/test.jl"};
Process pTest = Runtime.getRuntime().exec(params);
try {
if (pTest.waitFor() != 0) {
System.err.println("exit value = " + pTest.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(pTest.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line+"-");
}
System.out.println(stringBuffer.toString());
} catch (InterruptedException e) {
System.err.println(e);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Consider this changed (and working) implementation removing the too-early invocation of waitFor and exitValue:
public class Main {
public static void main(String[] args) {
try {
String[] params = {"C:/Program Files/Julia-0.4.1/bin/julia.exe",
"C:/Users/Thomas/Julia/test.jl"};
Process pTest = Runtime.getRuntime().exec(params);
BufferedReader in = new BufferedReader(new InputStreamReader(pTest.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
System.out.println("===");
System.out.println("Julia exit value = " + pTest.exitValue());
} catch (IOException e) {
e.printStackTrace();
}
}
}
This produced the following output with your test-script:
it's test1
===
Julia exit value = 0
I got it finally.
As julia.exe execute on the command prompt immediately, we must give admin privileges to the users of cmd.exe.
Related
I am writing a java program that will need to run a python script.
The script will print output which will java need to read to know the progress of the script.
To be able to pause the script while running I want it to ask for input once in a while, only when java give it input the script will keep going.
Here is my Java method:
private static void sevenTry(String[] strCommands) throws IOException {
Object oLock1 = new Object();
Object oLock2 = new Object();
ProcessBuilder pBuilder = new ProcessBuilder(strCommands);
pBuilder.redirectErrorStream(true);
Process proc = pBuilder.start();
Thread tReader = new Thread() {
#Override
public void run() {
System.out.println("~~tReader starting~~");
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
synchronized (oLock1) {
try {
String line = reader.readLine();
while (line != null && !line.trim().equals("--EOF--")) {
System.out.println("Stdout: " + line);
if (line.trim().equals("--INPUT--")) {
synchronized (oLock2) {
oLock2.notify();
}
oLock1.wait();
}
line = reader.readLine();
}
} catch (IOException e) {
System.out.println("tReader: " + e.getMessage());
} catch (InterruptedException e) {
System.out.println("tReader: " + e.getMessage());
} catch (Exception e) {
System.out.println("tReader: " + e.getMessage());
}
}
System.out.println("~~tReader end~~");
synchronized (oLock2) {
oLock2.notify();
}
}
};
Thread tWriter = new Thread() {
#Override
public void run() {
System.out.println("~~tWriter starting~~");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
String line, input;
Scanner scan = new Scanner(System.in);
synchronized (oLock2) {
try {
oLock2.wait();
} catch (InterruptedException e1) {
System.out.println("tWriter: " + e1.getMessage());
}
}
while (tReader.isAlive()) {
synchronized (oLock1) {
System.out.println("Java: insert input");
scan.hasNext();
input = scan.nextLine();
try {
writer.write(input + "\n");
writer.flush();
} catch (IOException e) {
System.out.println("tWriter: " + e.getMessage());
}
oLock1.notify();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
System.out.println("tWriter: " + e1.getMessage());
}
}
System.out.println("~~tWriter end~~");
}
};
tReader.start();
tWriter.start();
System.out.println("~~everything submitted~~");
try {
tReader.join();
tWriter.join();
System.out.println("~~finish~~");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This is my python script:
# coding=utf-8
import sys
print '1'
print '--INPUT--'
inum = sys.stdin.readline()
print '2'
print '--EOF--'
I tried running my code
sevenTry("python", "C:\\Testing.py");
but on java side it get stuck inside tReader at line:
String line = reader.readLine();
The program does work if i take out the input line from the python file
inum = sys.stdin.readline()
Using
inum = raw_input()
still bring up the same problem (im using python 2.7)
The most confusing part here that i even tried to test this with a java file (instead of python)
sevenTry("java", "-classpath", "C:\\class", "CheckCMD");
and it worked even with the input lines
import java.util.Scanner;
public class CheckCMD {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String line;
System.out.println("1");
System.out.println("--INPUT--");
in.hasNext();
line = in.nextLine();
System.out.println("2");
System.out.println("--EOF--");
}
}
As you may have noticed, this is a problem related to Python.
As described in https://unix.stackexchange.com/questions/182537/write-python-stdout-to-file-immediately,
" when process STDOUT is redirected to something other than a terminal, then the output is buffered into some OS-specific-sized buffer (perhaps 4k or 8k in many cases)."
So, you need to call sys.stdout.flush() after each invoke to print.
Or, as a better option, you can change the default behaviour for the process, using the -u param, to get unbuffered output.
Real Goal: create a program that calls other programs(lab exercises)
Current goal: Make Main.java run Lab4 a GUI program (Lab4Ans201506159.java - the filename)
Lab4Form and Lab4Intro are forms
here is the Main.java code
public class Main {
public static void main(String[] args) throws IOException {
// TODO code application logic here
Process p,p2,p3,p4;
p = Runtime.getRuntime().exec("javac Lab4Ans201506159.java");
//p3 = Runtime.getRuntime().exec("javac Lab4Ans201506159Form.java");
//p4 = Runtime.getRuntime().exec("javac Lab4Ans201506159Intro.java");
p2 = Runtime.getRuntime().exec("java Lab4Ans201506159");
//p2 = Runtime.getRuntime().exec("Lab4Ans201506159");
}
and here is the Lab4 code
Lab4Form and Lab4Intro are Frames
what Lab4 is trying to do displaying Lab4Intro, and when it is closed, Lab4Form would be visible
public class Lab4Ans201506159 {
public static void main(String[] args) throws InterruptedException {
Lab4Ans201506159Intro intro = new Lab4Ans201506159Intro();
intro.setLocationRelativeTo(null);
intro.setVisible(true);
Thread.sleep(2000);
//Lab4Ans201506159Form form = new Lab4Ans201506159Form();
while(intro.isActive())
{
}
if(intro.isActive() == false){
Lab4Ans201506159Form form = new Lab4Ans201506159Form();
form.setLocationRelativeTo(null);
form.setVisible(true);
}
}
Problem: Running Main.java will result to a "BUILD SUCCESSFUL" in the compiler but no GUI is displayed. I need answers why it does not display or work.
I suspect only the first Process is executed, in order to be sure, have you already tried to redirect the output of Runtime.exec to the standard output
something like that:
public static void main(String[] args) throws Exception {
System.setOut(new PrintStream(new FileOutputStream("log.txt")));
System.out.println("Init...");
try {
String line;
Process p = Runtime.getRuntime().exec( "javac Lab4Ans201506159.java" );
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()) );
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
Thread.sleep(1000);
Process p2 = Runtime.getRuntime().exec("java Lab4Ans201506159" );
BufferedReader in2 = new BufferedReader(
new InputStreamReader(p2.getInputStream()) );
while ((line = in2.readLine()) != null) {
System.out.println(line);
}
in2.close();
}
catch (Throwable e) {
e.printStacktrace();
}
}
like that you can verify what is going wrong...
good luck
I managed to finish my end goal which is to open Lab4. I sort of took a different method though. I suspect one of the reasons why it does not work is because my classpath must have been wrong. I could say that because I can't compile (javac) in CMD Prompt. So I fixed that, then I 'clean and build' (using Netbeans) the project(lab4,intro,form). After that, in the last line of the compiler there will be a line like "java -jar C:\sdfsafs\blablabal". That was the line I used inside runtime.exec() and it finally worked.
public static void main(String[] args) throws Exception {
try {
runProcess("java -jar \"C:\\Users\\Aldrin\\Desktop\\201506159AnsLab4\\dist\\201506159AnsLab4.jar\"");
//runProcess("dir");
//runProcess("java Lab4Ans201506159");
} catch (Exception e) {
e.printStackTrace();
}
}
I still have not answered why the original code does not work though.
I want a java program to execute the following shell command:
apktool.jar d /path/to/my/app.apk
This command perfectly works when executing it directly on command line.
Java Code:
public static void main(String[] args) {
String command = "apktool d /path/to/my/app.apk";
try {
Runtime.getRuntime().exec(command);
} catch (IOException e1) {
e1.printStackTrace();
}
}
There is no error, no exception. Nothing happens and i have the impression that I already searched the entire internet for a solution. Does anybody know what I am doing wrong? A simple command like
mkdir /path/to/a/new/folder
works without problems.
I tried the same using ProcessBuilder:
try {
Process process = new ProcessBuilder(command).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This time i only get "Cannot run program "apktool d /path/to/my/app.apk, No such file or directory". I can't even run the mkdir command.
You need to call the jar with java.exe, and you're not doing that. Also you need to trap the input and error streams from the process, something you can't do the way you're running this. Use ProcessBuilder instead, get your streams and then run the process.
For example (and I can only do a Windows example),
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class ProcessEg {
private static Process p;
public static void main(String[] args) {
String[] commands = {"cmd", "/c", "dir"};
ProcessBuilder pBuilder = new ProcessBuilder(commands);
pBuilder.redirectErrorStream();
try {
p = pBuilder.start();
InputStream in = p.getInputStream();
final Scanner scanner = new Scanner(in);
new Thread(new Runnable() {
public void run() {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
try {
int result = p.waitFor();
p.destroy();
System.out.println("exit result: " + result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Try doing it like this:
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec("./path/apktool d /path/to/my/app.apk");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
system.out.println(output.toString());
Creating first a process allows you to wait for a response and reads the output of the execution of your process.
If something is failing while running your shell command, you will have the error printed at the end.
Also, make sure your java program can access your shell script, or better provide the full path to it like:
./path/to/shell/apktool d /path/to/my/app.apk
i have a hello world class hworld.class which displays "Hello World" on the console. i am trying to run it from another class in console using the code
public class ftest2
{
public static void main(String[] arg)
{
System.out.println("NEW FILE PRINT LINE EXECUTED");
try {
Process pro1 = Runtime.getRuntime().exec("javac hworld.java");
pro1.waitFor();
Process pro2 = Runtime.getRuntime().exec("java hworld");
pro2.waitFor();
} catch (Exception e) {
System.out.println("Some Error");
e.printStackTrace();
}
} }
but when the file is executed, the output of Hello World is not displayed on the console.
the program just starts and displays
NEW FILE PRINT LINE EXECUTED
insted of
NEW FILE PRINT LINE EXECUTED
HELLO WORLD
how it would be possible to display the output of HELLO WORLD as well.
(it is example program. i want to display the output of a program within another program)
if there is another way to call a class within another class to display its output. then please mention it.
You need to read in the InputStream of the process, which is
The stream obtains data piped from the standard output stream of the
process represented by this Process object.
Source: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html#getInputStream()
Read InputStream and write out to System.out:
InputStream inputStream = process.getInputStream();
int b = -1;
while ( (b = inputStream.read()) != -1 ) {
System.out.write(b);
}
You need to redirect the inputstream of your process to System.out, for example:
public static void main(String[] arg) {
System.out.println("NEW FILE PRINT LINE EXECUTED");
try {
Process pro1 = Runtime.getRuntime().exec("javac hworld.java");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(pro1.getInputStream(), Charset.forName("UTF-8")))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Note: it uses the try with resources syntax of Java 7 but is easily transposable to Java 6- if necessary.
Might be you are getting exception and you've not printed it.
public class ftest2
{
public static void main(String[] arg)
{
System.out.println("NEW FILE PRINT LINE EXECUTED");
try {
Process pro1 = Runtime.getRuntime().exec("javac hworld.java");
pro1.waitFor();
Process pro2 = Runtime.getRuntime().exec("java hworld");
pro2.waitFor();
} catch (Exception e) {
System.out.println("Some Error");
e.printStackTrace();
}
}
}
and another way
public static void main(String[] arg)
{
System.out.println("NEW FILE PRINT LINE EXECUTED");
hworld.main(arg); // since main is a static method can be called w/o instance
}
I am building a Java program for automating a procedure in my server side. Normally I cd to Desktop/GIT/ and use this maven command "mvn integration-test -DskipTests -P interactive -e".
I am building a java program and I am trying to run that command line but so far I wasn't successful.
So far, here is the code:
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
Process theProcess = null;
try
{
theProcess = Runtime.getRuntime().exec("mvn integration-test -DskipTests -P interactive -e");
}
catch(IOException e)
{
System.err.println("Error on exec() method");
e.printStackTrace();
}
// read from the called program's standard output stream
try
{
inStream = new BufferedReader(new InputStreamReader( theProcess.getInputStream()));
System.out.println(inStream.readLine());
}
catch(IOException e)
{
System.err.println("Error on inStream.readLine()");
e.printStackTrace();
}
break;
}
}
in.close();
}
You should check out maven embedder; which is exactly the tool which you should use in case of embedding maven.
OK apparently maven embedder is not supported any more. Probably you can still get it working though, but I rather created a small sample for you which should work. Of course, replace the path for Maven:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Q {
public static void main(String[] args) throws IOException, InterruptedException {
Process p = null;
try {
p = Runtime.getRuntime().exec("C:/Applications/apache-maven-3.0.3/bin/mvn.bat integration-test -DskipTests -P interactive -e");
} catch (IOException e) {
System.err.println("Error on exec() method");
e.printStackTrace();
}
copy(p.getInputStream(), System.out);
p.waitFor();
}
static void copy(InputStream in, OutputStream out) throws IOException {
while (true) {
int c = in.read();
if (c == -1)
break;
out.write((char) c);
}
}
}
If you want to run it with other configuration options, try Jenkins as the continous integration tool. It is free and can be used with Tomcat.
I managed to run the mvn using the following code:
(I use this command: Runtime.getRuntime().exec(cmd);)
import java.io.*;
import java.util.ArrayList;
public class RunMvnFromJava {
static public String[] runCommand(String cmd)throws IOException
{
// The actual procedure for process execution:
//runCommand(String cmd);
// Create a list for storing output.
ArrayList list = new ArrayList();
// Execute a command and get its process handle
Process proc = Runtime.getRuntime().exec(cmd);
// Get the handle for the processes InputStream
InputStream istr = proc.getInputStream();
// Create a BufferedReader and specify it reads
// from an input stream.
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
String str; // Temporary String variable
// Read to Temp Variable, Check for null then
// add to (ArrayList)list
while ((str = br.readLine()) != null)
list.add(str);
// Wait for process to terminate and catch any Exceptions.
try {
proc.waitFor();
}
catch (InterruptedException e) {
System.err.println("Process was interrupted");
}
// Note: proc.exitValue() returns the exit value.
// (Use if required)
br.close(); // Done.
// Convert the list to a string and return
return (String[])list.toArray(new String[0]);
}
// Actual execution starts here
public static void main(String args[]) throws IOException
{
try
{
// Run and get the output.
String outlist[] = runCommand("mvn integration-test -DskipTests -P interactive -e");
// Print the output to screen character by character.
// Safe and not very inefficient.
for (int i = 0; i < outlist.length; i++)
System.out.println(outlist[i]);
}
catch (IOException e) {
System.err.println(e);
}
}
}
For windows, Try this
Process p=Runtime.getRuntime().exec("cmd.exe /c mvn install:install-file -Dfile=C:\\Users\\Desktop\\Desktop\\sqljdbc4-4.0.jar -Dpackaging=jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0");
For linux, **"cmd.exe /c"** is not needed.
try this:
List<String> commands=new ArrayList<>();
commands.add("mvn");
commands.add("-f");
commands.add();
commnads.add("integration-test");
commands.add("-DskipTests");
commands.add("-P");
commands.add("interactive");
commands.add("-e");
ProcessBuilder pb=new ProcessBuilder(commands);
pb.start();``