I want to execute another Java program in my program. I have taken reference from here. For testing I have pasted same code as accepted answer shows.I have passed a simple HelloWorld program. Program compiles perfectly but gives Main class not found error.
Here is my code:
Server.java
public static void main(String args[]) {
try {
runProcess("javac D:\\HelloWorld.java");
runProcess("java D:\\HelloWorld");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}
HelloWorld.java:
`public static void main(String args[]){
System.out.println("Hello World!");
}`
Output:
exitValue() 0 for javac
stderr: Error: Could not find or load main class D:\HelloWorld
exitValue() 1 for java
Compiling and running same program on CMD or IDE gives perfect output.
You want to start main from HelloWorld class? I think, in that case you should run program something like this:
java -cp 'D:\' HelloWorld
So, you need to specify ClassPath - 'D:\' and entry class name from classpath - HelloWorld.
Why try to do things the hard way? Use the inline compiler API and then simply execute the main() method on your new class after loading the class itself into your root classloader.
Related
I am trying to execute git clone in Java using Java's Runtime.getRuntime().exec() in Linux and the interpreter is /bin/bash. However, I get "no such file or directory" in error stream. I searched the stackoverflow and found no answer can solve my problem. Here is my program in Test.java:
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException, InterruptedException {
String version = "10.1.1";
String repo_url = "https://github.com/postcss/postcss-url";
String directory = "./tmp";
String cmd = "\"/usr/bin/git clone --branch " + version + " " + repo_url + " --depth=1 " + directory + "\"";
// String cmd = "git -h";
String interpreter = "/bin/bash";
cmd = " -c "+ cmd;
System.out.println(interpreter + cmd);
Process process = Runtime.getRuntime().exec(new String[]{ interpreter, cmd });
print(process.getInputStream());
print(process.getErrorStream());
process.waitFor();
int exitStatus = process.exitValue();
System.out.println("exit status: " + exitStatus);
File[] files = new File(directory).listFiles();
System.out.println("number of files in the directory: " + files.length);
}
public static void print(InputStream input) {
new Thread(new Runnable() {
#Override
public void run() {
BufferedReader bf = new BufferedReader(new InputStreamReader(input));
String line = null;
try {
while ((line = bf.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("IOException");
}
}
}).start();
}
}
./tmp is surely an empty directory. I use javac Test.java to compile the code and then run java Test. Besides, I tried sudo java Test and got the same result. I get output like this:
/bin/bash -c "/usr/bin/git clone --branch 10.1.1 https://github.com/postcss/postcss-url --depth=1 ./tmp"
exit status: 127
/bin/bash: -c "/usr/bin/git clone --branch 10.1.1 https://github.com/postcss/postcss-url --depth=1 ./tmp": No such file or directory
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:18)
When I use "git -h" or "ls", it works just fine. But, this command /bin/bash -c "/usr/bin/git clone --branch 10.1.1 https://github.com/postcss/postcss-url --depth=1 ./tmp" works in shell but failed in Java. How can I solve this problem?
You have to pass -c as a separate parameter, and you shouldn't add literal double quotes to the command:
new String[]{ "bash", "-c", "git clone ..." }
This is because spaces and quotes are shell syntax, and Runtime.exec doesn't invoke one to run the command (which happens to be a shell invocation, but that's unrelated)
I have a simple script and I want to call it from my Java code. The script does not run properly.
The script is very simple:
mkdir 0000000;
public static void main(String[] args) throws Exception{
String path = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
String command = "C:\\test\\test.ps1";
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(path + " " + command);
proc.destroy();
}
The dir "0000000" is not created. I use JDK 7, windows 10.
Any suggestion would be gratefully appreciated.
I changed the code as below and finally it worked!
public static void main(String[] args) throws Exception{
String path = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
String command1 ="cmd /c \"cd C:\\test && " + path + " /c .\\test.ps1\"";
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command1);
Thread.sleep(2000);
proc.destroy();
}
exec() runs the process asynchronously, so the subsequent proc.destroy() terminates it right away before it can do anything. If you run the program from an interactive shell simply removing proc.destroy() would mitigate the issue, but to actually fix it you need to wait for the external process to finish. You may also want to catch the exception exec() (or waitFor()) could throw.
import java.io.*;
public static void main(String[] args) throws Exception{
String path = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
String command = "C:\\test\\test.ps1";
Runtime runtime = Runtime.getRuntime();
try {
Process proc = runtime.exec(path + " " + command);
proc.waitFor();
} catch (Exception e) {
// do exception handling here
}
}
I'm trying to run a java program, called Test.java from another java program Demo.java. Both programs are in the same package, I'm doing something like this:
try{
System.out.println("Executing another client");
runProcess("javac -cp gridgain-examples C:/Users/Desktop/gridgain/examples/src/main/java/apache/ignite/schemas/Test.java");
System.out.println("******");
runProcess("java -cp gridgain-examples C:/Users/Desktop/gridgain/examples/src/main/java/apache/ignite/schemas/Test.java");
} catch(Exception e) {
e.printStackTrace();
}
And the runProcess and printlines methods are:
private static void printLines(String cmd, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(cmd + " " + line);
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}
But it's not executing. Please tell me how to do it?
Have you tried "C:\Users\Desktop\gridgain\examples\src\main\java\apache\ignite\schemas\Test.java"?
I'd comment this but don't have the reputation :(
I am trying to run a java file through another java program . this is my code:
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}
public static void main(String[] args) {
String[] credentials=new String[4];int k=0;
for (String s: args) {
System.out.println(s);
credentials[k]=s;k++;
if(k==4)
break;
}
try {
//runProcess("javac test2.java");
runProcess("java test2 "+credentials[0]+" "+credentials[1]+" "+credentials[2]+" "+credentials[3]+" ");
} catch (Exception e) {
e.printStackTrace();
}System.out.println("hI");
}
The problem is I have kept both the files(which I execute and the one which is executed by that file) in same folder but when I run this file it displays class not found error.. for test2.java and it probably due to the fact that it searches the class file test2.class in some other folder . what should I do?
my file structure:
x/y/Laj.java
x/y/test2.java
and it seaches the class file in x folder?
Use
Runtime.getRuntime().exec(command, null, workingDir);
where workingDir is :
workingDir- the working directory of the subprocess, or null if the subprocess should inherit the working directory of the current process.
If you run the first program using
java x.y.Laj
then you should change the line where you compose the command:
runProcess("java x.y.test2 "+credentials[0]+...
** Later **
Since the x.y is just a red herring, try setting the system property:
runProcess("java -Djava.class.path=\"/.../x/y\" " + credentials[0]+...
For production (start of Laj not from an IDE) consider setting CLASSPATH so that all class files can be found via the class path.
I am trying to make a java application which runs another java program at certain point of event occurrence . As I have to run this process in background I am using & symbol . This is part of the application .
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
// pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}
runProcess("javac test2.java");
runProcess("java test2 "+id+" "+pass+" "+choice+" &");//Id,pass,choice are arguments of java program
The problem I am facing is If I am print the lines os that program my actual application does not move to next part until my background process is over which takes long time and if I omit these output lines then the background process exits and gives this error :
java.lang.IllegalThreadStateException: process hasn't exited
And If I use pro.waitFor(); then again the first problem .What should I do?