How to execute a java program from another java program in eclipse - java

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 :(

Related

Android trying to run an unix executable: syntax error: '__TEXT' unexpected

While trying to run a simple HelloWorld Unix executable:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
}
(Compiled through g++ HelloWorld.cpp -o HelloWorld (on Mac). The program works on my Mac by using ./HelloWorld and by letting it run through a Java environment:
(HelloWorld.java -> working)
public class HelloWorld
{
public static void main(String args[])
{
String[] command = new String[]{"/system/bin/chmod", "744",
"/Developer/Java/HelloWorld" };
execute(command);
command = new String[]{"./HelloWorld"};
execute(command);
}
public static void execute(String...command)
{
StringBuilder log = new StringBuilder();
try
{
BufferedReader br;
String line;
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process proc = builder.start();
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ( (line = br.readLine()) != null)
System.out.println(line + "\n");
}
catch (IOException e) {
log.append("General IOException:\n" + e.getMessage() + "\n");
}
catch (InterruptedException e) {
log.append("Error:\n" + e.getMessage() + "\n");
}
}
}
In my java code for the Android app, I first copied the executable to getBaseContext().getDataDir(), this works fine. To change the permissions I'm using the following:
command = new String[]{"/system/bin/chmod", "744",
getAssetsPath() + "/HelloWorld" };
execute(pv, command);
and trying to run the program through:
command = new String[]{"." + getAssetsPath() + "/HelloWorld"};
terminal(tv, command);
Note, that I use the following functions:
public File getAssetsDir() {
return getBaseContext().getDataDir();
}
public String getAssetsPath() {
return getAssetsDir().getAbsolutePath();
}
public void execute(TextView tv, String...command)
{
tv.setText("Starting Terminal.\n");
StringBuilder log = new StringBuilder();
try
{
BufferedReader br;
String line;
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process proc = builder.start();
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ( (line = br.readLine()) != null)
log.append(line + "\n");
}
catch (IOException e) {
log.append("General IOException:\n" + e.getMessage() + "\n");
}
catch (InterruptedException e) {
log.append("Error:\n" + e.getMessage() + "\n");
}
tv.setText(log.toString());
}
As already said this will result in the following error inside the TextView (tested on Pixel_XL_API_25):
syntax error: '__TEXT' unexpected
Hope you can help me find the cause of this problem. Thanks in advance.
Edit:
If you want to know why I want to use a Unix executable for such simple things: This is just for testing. Actually, I want to run other more complex programs/libraries which will be hard to use through ndk, because there is no cmake for this library, only "normal" make.
The answer is, that the compiler isn't the right compiler to use. If you want to run it on another device you have ti compile it there or use some cross compiler, I guess.
The question is now: Which compiler would work? I found this suggestion (How to compile and run a C/C++ program on the Android system):
arm-linux-gnueabi-g++ -static -march=armv7-a HelloWorld.c -o HelloWorld
But that won't work in this specific constellation.

How to run a MySQL script using ProcessBuilder?

I have a SQL script which I would like to execute from a Java class, running on Windows. I am currently trying to do this using ProcessBuilder in the following function:
public static boolean runSqlScript(String filename, String user, String password) {
ProcessBuilder pb = new ProcessBuilder("mysql", "-u"+user, "-p"+password, "< "+ filename);
try {
Process pr = pb.start();
BufferedReader errors = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
BufferedReader output = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while (pr.isAlive()) {
try {
System.err.println(errors.readLine());
System.out.println(output.readLine());
Thread.sleep(10);
} catch (InterruptedException e) {
break;
}
}
System.err.println(errors.readLine());
System.out.println(output.readLine());
int status = pr.exitValue();
return (status == 0);
} catch (IOException e) {
System.err.println("Error running command: " + e.getMessage());
return false;
}
}
The filename is the absolute path to the script, and the user and password are verified correct. But when I run this, I get the error:
ERROR 1102 (42000): Incorrect database name '< c:/path/to/script.sql'
Why is it interpreting that as a database name rather than a command line argument? Can I use ProcessBuilder to run the script like this?
You need to add database name and it will work ProcessBuilder pb =
new ProcessBuilder("cmd", "/c", "mysql", "-u"+user, "-p"+password,"dbname", " < "+ filename);
Runtime.exec() can also be used to send commands, which doesn't seem to have the same issue as ProcessBuilder:
public static boolean runSqlScriptRuntime(String filename, String user, String password) {
Runtime rt = Runtime.getRuntime();
try {
String cmd = "cmd /c mysql -u " + user + " -p" + password + " < " + filename;
System.out.println(cmd);
Process pr = rt.exec(cmd);
BufferedReader errors = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
BufferedReader output = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while (pr.isAlive()) {
try {
System.err.println(errors.readLine());
System.out.println(output.readLine());
Thread.sleep(10);
} catch (InterruptedException e) {
break;
}
}
System.err.println(errors.readLine());
System.out.println(output.readLine());
int status = pr.exitValue();
return (status == 0);
} catch (IOException e) {
System.err.println("Error running command: " + e.getMessage());
return false;
}
}
An alternative to trying to simulate command-line arguments is to call the SQL script from inside mysql, as described here.
public static boolean runSqlScript(String filename, String user, String password) {
ProcessBuilder pb = new ProcessBuilder("mysql", "-u"+user, "-p"+password);
try {
Process pr = pb.start();
BufferedReader errors = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
BufferedReader output = new BufferedReader(new InputStreamReader(pr.getInputStream()));
BufferedWriter input = new BufferedWriter(new OutputStreamWriter(pr.getOutputStream()));
input.write("source " + filename + ";");
input.flush();
input.write("quit;");
input.flush();
input.close();
while (pr.isAlive()) {
try {
System.err.println(errors.readLine());
System.out.println(output.readLine());
Thread.sleep(10);
} catch (InterruptedException e) {
break;
}
}
System.err.println(errors.readLine());
System.out.println(output.readLine());
int status = pr.exitValue();
return (status == 0);
} catch (IOException e) {
System.err.println("Error running command: " + e.getMessage());
return false;
}
}
This will run MySQL and then call the script. However, I originally was using ProcessBuilder because I thought the script could be handled in a single command line - with a solution like this, it probably makes more sense to just use JDBC.

Running Java Program in another Program gives error

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.

How to change path while running java file?

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.

Running Background java program

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?

Categories

Resources