C program compilation from a java program - java

I am trying to compile a c program from a java program on Linux platform. My snippet is.
ProcessBuilder processBuilder = new ProcessBuilder("/usr/bin/gcc",
"-c","/hipad/UserProject/example.c");
Process proc = processBuilder.start();
There is no error during compilation of java program but I am not able to get .o file. I tried to find out solutions but no one is working.
Any suggestion.....

The default working directory of a child process is what ever directory the Java process has as a working directory, which usually is where it was launched from. And by default gcc writes output files to current working directory. That's where you should find example.o.
There are two simple ways to solve this. You can give gcc -o option and full path and name of desired output file, or you can set working directory of child process, like this:
ProcessBuilder processBuilder =
new ProcessBuilder("/usr/bin/gcc", "-c","example.c"); // source in working dir
processBuilder.directory(new File ("/hipad/UserProject")); // or whatever
Process proc = processBuilder.start();
See ProcessBuilder javadoc for more info.

Related

Java run Python script Issue

ProcessBuilder pb = new ProcessBuilder("C:\\xxxxxxx\\python.exe", "C:\\xxxxxxxxxx\\1.py");
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
Process p = pb.start();
I am trying to run Python script from my Java program. The problem is, java run doesn't give me any result. In Python script, there is an OCR operation and I am writing a txt file.
CMD - Manually - It runs OK
Python IDLE - Manually - It runs OK
.bat doesn't work. with administrative rights doesn't work.
Java run doesn't work.
I need help, I need to run the script from java program.
I solved the problem.
The problem is;
ProcessBuilder pb = new ProcessBuilder("C:\\xxxxxxx\\python.exe", "C:\\xxxxxxxxxx\\1.py");
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
Process p = pb.start();
When you run this code, python script will process operations in that directory, I mean in your Java class' directory. No matter where py file is.
In my case, there were 'image.save("x.png")' lines in the python script. I hoped that images will be saved in the directory where the py file is. But it is not like that.

Java Shell Command not Running from Current Directory

In this question it shows that when you run a shell command from Java, it runs from the current directory. When I run the command javac Program.java from my program, it shows the error (from the standard error stream):
javac: file not found: Program.java
Usage: javac <options> <source files>
use -help for a list of possible options
However, when I run the same exact command from the actual Terminal, it works fine and saves the .class file in the default directory. This is the code:
Runtime rt = Runtime.getRuntime();
String command = "javac Program.java";
Process proc = rt.exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
proc.waitFor();
Any ideas why it works when I type it in the actual Terminal, but not when I run it from my program? I am running a Max OS X Mountain Lion (10.6)
Thanks
You can try to print the path in your programm ,use new File(".").getAbsolutePath() ,if you are in a ide ,the path may be in the root of the project rather than in the path of the current java file
Your program is probably being run from a different directory. Your IDE (such as Eclipse) is probably is running from one location, and knows the directory structure to access your program files.
The easiest, quickest solution is to just write the fully-qualified file path for Program.java.
The alternate is to find out what the current directory is. So, perhaps run pwd the same way you are running javac Program.java from within your program's code? Then you can see what directory your program is actually being run from. Once you know that, you can write the appropriate directory structure.
For example, if pwd reveals that you are actually 2 directories above where Program.java is, then you can put those directories in the command like this: javac ./dir1/dir2/Program.java.
To change the directory Eclipse runs from, see this question Set the execution directory in Eclipse?
The reason my code was not working was because I was running it in Eclipse IDE, and that messes up the directory the program is running from. To fix that program, I changed the command to javac -d . src/Program.java. If I export the program into a .jar file and run it in the desktop, my original command will do just fine.
Thanks to saka1029 for helping me!

How to execute the shell script program file from the Java class

I have written a shell script file which extracts the files, Please see below.
File Name: unzip.sh
#/bin/sh
cd /home/zip;
UNZIPDIR=/home/unzip/;
for i in *.zip; do
unzip "$i" -d "$UNZIPDIR"
rm "$i";
done;
This shell script executes sucessfuly on putty,
$> ./zip.sh
As i wanted to execute this script from my java class while i have tried several ways to invoke/execute the shell script file but it's not executing. Please see below java code.
//First try
File executorDirectory = new File("/home/zip");
ProcessBuilder processBuilder = new ProcessBuilder("./unzip.sh");
processBuilder.directory(executorDirectory);
Process p = processBuilder.start();
p.waitFor()
//Second try
Process p = Runtime.getRuntime().exec("/home/zip/unzip.sh");
The problem is that you fail to account for the process' standard output/error (as mentioned by #Yazan in the comments). You need to .get{Output,Error}Stream() from the created process and read from them (even if it is only to discard it).
The real problem however is that you use an external shell script for something which is entirely doable in Java itself. See this page which gives an example of how to extract a zip file entirely with Java code; to delete a file, use Files.delete().

Run jar file from java application [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Run Java program into another Program
i try to run jar file from java application which was created in eclipse.
when i run jar file using below source code then fire Unable to access jarfile error
Process process = run.exec("java -jar TestJava.jar");
InputStream inError = process.getErrorStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inError));
System.out.println("Error=" + bufferedReader.readLine());
Sounds like TestJava.jar is in a different directory. If you're running this code within Eclipse, then the present working directory is going to be the same as your Eclipse project's folder (unless you've configured it differently, this is Eclipse's default run location). Either specify a path to TestJava.jar via an absolute path or a path relative to the present working directory.
One other thing you'll need to be mindful of - you need to consume both the error stream and the output stream of the Process you're creating. The default output/error stream buffer sizes of Process instances are not very big and, if full, will cause that Process to block indefinitely for more buffer space. I recommend consuming each stream in a separate Thread.
Set the working directory where this process should run. Set the working directory using the below statement.
Runtime.getRuntime().exec(command, null, new File("path_to_directory"));
First try the java -jar command on cmd window and see if you can run TestJava.jar. Then try running the same command from your code.
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("java -jar TestJava.jar");
System.exit(0);
You need to supply the full path to the Java command.
For example, under windows you'd need something like
C:/Program Files/java/jre/bin/java.exe
ProcessBuilder & Runtime.exec don't take the system path into account when trying to execute your command

Runtime.exec doesn't compile java file

I compile java file by Runtime.exec("javac MyFrog.java");
It says no errors, doesn't output anything, but doesn't create MyFrog.class file.
if i write Runtime.exec("javac") it outputs to output some help text.
So I understand that program is working, but don't create class file. Permissions are ok.
javac -verbose should give you lot more information, specifically the directory where the file is created. Since you are able to recognize output help text without any parameters, I assume you are capturing the process's stderr and assume you are doing the same for stdout as well (though javac does not seem to write anything to stdout).
Where are you checking for the existence of the .class file? It is created in the same directory as the .java file. If MyFrog.java has a package declaration it will not be created in the package sub-dir; for that you have to use -d argument.
make sure that MyFrog.java is present in working directory
Try javac -verbose and make sure your classpath is set correct.
You can use ProcessBuilder or Runtime.exec() method to create new process,
String []cmd={"javac","Foo.java"};
Process proc=Runtime.getRuntime().exec(cmd);
proc.waitFor();
Or use ProcessBuilder
ProcessBuilder pb = new ProcessBuilder("javac.exe","-verbose", "Foo.java");
pb.redirectErrorStream(true);
Process p = pb.start();
p.waitFor();
InputStream inp=p.getInputStream();
int no=inp.read();
while(no!=-1)
{
System.out.print((char)no);
no=inp.read();
}
I always find this resource answers all questions about Java exec.

Categories