Run jar file from java application [duplicate] - java

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

Related

Running python script from jar file

I have been working on java app that uses python script to run some 3d visualization, it worked when I was running it from intellij but once I created jar file it just doesn't run. OS: MAC OS
How I run script:
Process p1 = Runtime.getRuntime().exec("python3 vizualize3D.py");
The problem had multiple layers and solutions:
1. I didn't put .py file in jar build config
2. After putting it I always got an exception that it is null because of a typo in code
3. After trying many ways to run it this one worked Cannot run python script from java jar
. The important thing is to check if you added py file to the build config and to run it in a proper way since python cannot runt files from the zip and compressed states.
Assuming the script is in the jar file, you can get an input stream from the resource, and use it as the input to a Process created from the python interpreter:
// Note: the path to the script here is relative to the current class
// and follows strict resource name rules, since this is in a jar file
InputStream script = getClass().getResourceAsStream("visualize3D.py");
// The following creates a process to run python3.
// This assumes python3 is on the system path. Provide the full
// path to the python3 interpreter (e.g. /usr/bin/python3) if it's
// not on the path.
// The - option to python3 instructs it to execute a script provided
// as standard input.
Process process = new ProcessBuilder("python3", "-")
.start() ;
OutputStream out = process.getOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
while((read = script.read(buffer)) != -1) {
pos.write(buffer, 0, read);
}
script.close();
For details on getting the correct path for the script, see How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application?

How to run a C++ exe file from Java?

I want to open an EXE file from a Java program. I tried 2 procedures.
The program can run some programs, like NotePad++, but cannot run my C++ EXE file. I tried:
Process exec = Runtime.getRuntime().exec(file.getAbsolutePath());
ProcessBuilder processBuilder = new ProcessBuilder(file.getAbsolutePath());
but neither of the above work. No exception is thrown, and exec.isAlive = true.
Your mistake is that you took the absolute path in the first procedure.
Try using a relative path, I just tested and it worked just fine.
This also works for me (using 2 backslashs').
Runtime.getRuntime().exec("C:\\Program Files\\DDNet\\DDNet.exe");
Kind regards

Controlling output file of a java jar using command line

I am using a .jar file, but unfortunatley as a black box, i.e. I do not know what exactly is in there nor how it all works.
I am sending commands to the Mac terminal from a Python script. I enter the following command:
java -jar jarfile.jar req_data /abs_path/to/required/data input path/to_my_/input/file.txt
This does what I need: analyses input using the 'black box' and creates and new file with analysis output. This new file is created in the folder where jarfile.jar is located.
I want to have this file put somewhere else upon creation.
I have tried using the > operator, specifying a path, e.g.:
java -jar jarfile.jar req_data /abs_path/to/required/data input path/to_my_/input/file.txt > /output/path/
this created a file in my desired location, but it was simply the message from Terminal, saying "The operation was carried out successfully" - the analysis results file was created in the same folder as before.
I tried %*> too, but it threw an error.
As a poor workaround I now have a function, which retrospectively finds and moves all the newly created files (analysis output) to my desired folder.
Is there a way to control the output files with the command line within the original command? Or is it something that is specified somewhere in my jar file? My problem is that editing it is not allowed.
I'm new to python. However, I may suggest to try few things, if they can work for you. Apology me, if does not work! I believe that you have already done the following step:
import subprocess
subprocess.call(['java', '-jar', 'Blender.jar'])
Like, if you have a properly configured jar path, then can run jar directly.
Secondly, look at the cwd parameter (is used for executable). Include a cwd param as x
def run_command(command, **x):
with subprocess.Popen(command,...., **x) as p:
for run_command specify the path of either the working directory (possibly it should be) or the full system path. I'm not sure, just try both.
for outputline in run_command(r'java -jar jarfilepath', cwd=r'workingdirpath', universal_newlines=True):
print(outputline, end='')
Alternatively, you can try to run command from the directory in which you wish to store output file. Try: run the popen as
subprocess.Popen(r'directory of running command', cwd=r'workingdir')
where workingdir could be your current directory path.
If it does not work, try without r'. If still does not work, try doubling slash in the path like (C:\\ abc\\def)

C program compilation from a java program

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.

Running .jar file within JSP page

I'm trying to develop a website that takes user input and converts to a text file. The text file is then used as an input for a .jar file. (e.g. java -jar encoder.jar -i text.txt), the jar then outputs a .bin file for the user to download.
This jar is designed to be run from command line and I really don't know the best way to implement it within a .jsp page. I have created a few java test classes but nothing has worked so far.
Does anyone have any suggestions on possible methods?
An alternative to running it as an external process is to invoke its main class in the current JVM:
Extract/open META-INF/MANIFEST.MF of the jar
Identify the Main-Class:. Say it is called EncoderMainClass
Invoke its main method: EncoderMainClass.main("-i", "text.txt")
This aught to be faster because a new OS process does not need to be created, but there may be security considerations.
Have you tried somrthing like this,
Create a java file
use a ProcessBuilder and start a new JVM.
Here is something to get you started:
ProcessBuilder pb = new ProcessBuilder("/path/to/java", "-jar", "your.jar", "thetextfile.txt");
pb.directory(new File("preferred/working/directory"));
Process p = pb.start();
ps: do handle to destroy process else it will eat up all memory
You can put this jar to the web application on the classpath and use it's class and methods. Better if you have javadoc if you don't have sources. But even if not in classpath you can try the example or this example.

Categories