how to execute jar file using java [duplicate] - java

How could I run a local jar file from a java program?
The jar file is not in the class-path of the Java caller program.

I suggest you 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");
pb.directory(new File("preferred/working/directory"));
Process p = pb.start();

Process proc = Runtime.getRuntime().exec("java -jar Validate.jar");
proc.waitFor();
// Then retreive the process output
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
byte b[]=new byte[in.available()];
in.read(b,0,b.length);
System.out.println(new String(b));
byte c[]=new byte[err.available()];
err.read(c,0,c.length);
System.out.println(new String(c));

First, the description of your problem is a bit unclear. I don't understand if you want to load the classes from the jar file to use in your application or the jar contains a main file you want to run. I will assume it is the second.
If so, you have a lot of options here.
The simplest one would be the following:
String filePath; //where your jar is located.
Runtime.exec(" java -jar " + filepath);
Voila...
If you don't need to run the jar file but rather load the classes out of it, let me know.

Could something like the following be useful?
http://download.oracle.com/javase/tutorial/deployment/jar/jarclassloader.html

Another way to do on windows is:
Runtime.getRuntime().exec("cmd /c start jarFile");
this way you can set priority of your process as well (normal/low/etc)

You can run a jar file from where ever you want by using only this one line code.
Desktop.getDesktop().open(new File("D:/FormsDesktop.jar"));
where
new File("your path to jar")
Hope it helps.
Thanks.

Add jar library to your project
Import main class (see manifest in jar file)
Invoke static method main with arguments
String args[] = {"-emaple","value"};
PortMapperStarter.main(args);

To run an executable jar from inside your java application, you can copy the JarClassLoader from https://docs.oracle.com/javase/tutorial/deployment/jar/examples/JarClassLoader.java
Use it like this. In this snippet, jarUrl is the URL to download the jar from, for example file:/tmp/my-jar.jar and args is the array of strings you want to pass as command line arguments to the jar.
JarClassLoader loader = new JarClassLoader(jarUrl);
String main = loader.getMainClassName();
loader.invokeClass(main, args);
Keep in mind that you're now inserting someone else's binary into your code. If it gets stuck in an infinite loop, your Thread hangs, if it calls System.exit(), your JVM exits.

This is my appriach, which I consider is more complete:
public static Process exec(String path, String filename) throws IOException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome +
File.separator + "bin" +
File.separator + "java";
ProcessBuilder pb = new ProcessBuilder(javaBin, "-jar", path+filename);
return pb.start();
}

1) Set the class path from environment variables
2) Go to the folder where your jar file exists
3) Run the following commands through command prompt
java -jar jarfilename

Related

Jarring All files in a directory based on extension

I am trying to jar all the files in a folder with the jar command using Java as follows,
jar -cvf /Abhishek/logs.jar my_directory/logs/*.logs*
I am using Java to execute this.
String cmd[] = {"jar", "-cvf", "/Abhishek/logs.jar", "my_directory/logs/*.logs*"};
pb = Runtime.getRuntime().exec(cmd);
but only the manifest is getting stored in the jar.
added manifest
When I extract the jar file, I am getting the manifest file.
So I had a doubt regarding
*log.*
Is this type of syntax allowed to be used?
Cause it worked fine in the terminal.
Could someone shed some light into this?
Thank you.
On Linux, file globbing is done by the shell. So when you enter *.log at the terminal, the shell will expand it to the list of matching files. Which is then passed to the program.
If you execute the program directly, you would have to expand the pattern yourself. Or you could let the shell execute it with a command similar to
String cmd[] = {"sh", "-c", "jar -cvf /Abhishek/logs.jar my_directory/logs/*.logs*"};
You may want to just use the same classes in the java.util.jar package that the jar command uses. This will avoid a second Java process and will avoid relying on shell expansion:
try (JarOutputStream jar = new JarOutputStream(
new BufferedOutputStream(
Files.newOutputStream(
Paths.get("/Abhishek/logs.jar"))));
DirectoryStream<Path> dir = Files.newDirectoryStream(
Paths.get("my_directory/logs"), "*.logs*")) {
for (Path file : dir) {
BasicFileAttributes attr =
Files.readAttributes(file, BasicFileAttributes.class);
String name = file.toString();
if (attr.isDirectory()) {
name = name + "/";
}
JarEntry entry = new JarEntry(name);
entry.setLastModifiedTime(attr.lastModifiedTime());
entry.setLastAccessTime(attr.lastAccessTime());
entry.setCreationTime(attr.creationTime());
entry.setSize(attr.size());
jar.putNextEntry(entry);
Files.copy(file, jar);
}
}

Runtime.exec(String) limiting String

I'm trying to use the Java function Runetime.exec(String) to run a program in the startup folder of a windows 7 computer like so:
Runtime.getRuntime().exec(runner.getPath() + "\\run.bat");
And when I run this I get an error saying the command cannot be run:
Exception in thread "main" java.io.IOException: Cannot run program ""C:\Users\ly
ndsey\AppData\Roaming\Microsoft\Windows\Start": CreateProcess error=2, The syste
m cannot find the file specified
As you can see, the file name is cut off at the "\Windows\Start" when it should continue to "\Windows\Startup\run.bat".. Is there an alternative I can use?
Considering runner as a File instance, this should work.
Desktop.getDesktop().open(new File(runner, "run.bat"));
It uses Desktop class instead of Runtime, so you don't have to convert your File (runner) to its String representation (which is error prone). Runner is now used 'as is' as the parent directory of the "run.bat" you want to execute.
Other advantage of Desktop class : you can now open any file you want.
As an alternative you can use ProcessBuilder. I feel ProcessBuilder is more safe than Runtime.getRuntime().exec http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
String[] command = {"CMD", "/C", "dir"};
ProcessBuilder pb = new ProcessBuilder( command );
//set up your work directory if needed
pb.directory(new File("c:\\path"));
Process process = pb.start();
as i can see from the error you give, and i hope it's a copy past, you string runner.getPath() for some reason start and end with "\"" which make the whole path invalid. check that and remove it if needed
if you have the file already and you just need it's path you can use
runner.getAbsolutePath()
also, if runner is a file, getPath will give you the file path including the path, so your code will surely won't work. instead use:
String path = runner.getPath();
path = path.substring(0, path.lastIndexOf("\\")) + "\\run.bat";
Runtime.getRuntime().exec(path);
You should avoid the exec(String) method, which attempts to parse the entire string into command + arguments. The safe option is exec(String[]), which presupposes the first array element is the command and the rest are arguments.
So, writing
Runtime.getRuntime.exec(new String[] { yourCommandString })
is a surefire way of getting the right message across.

Calling jar in my java code

I want to use a jar file Command.jar in my java code. When I run Command.jar from command line
like this java -jar Command.jar "Param1" it works well. But when I try to run it in my java code using either Process builder or Runtime.getRuntime().exec it does not work.
I tried this -
List <String> command = new ArrayList<String>();
command.add("java -jar");
command.add("Command.jar");
command.add("Param1");
ProcessBuilder builder = new ProcessBuilder(command);
try {
Process process = builder.start();
} catch (IOException e) {
}
It does not work. I also tried this:
Runtime.getRuntime().exec("java -jar Command.jar Param1");
But no luck. Please tell me where I am doing wrong
This is incorrect:
command.add("java -jar");
It should be
command.add("java");
command.add("-jar");
But there may be other problems as well. For instance java may not be accessible via the search path given by the PATH environment variable. Or Command.jar may not be in the current directory.
You need to see what (if anything) is being written by the java command to its standard output and/or standard error streams.
it does not work
does not tell us how to help you. You'll need to give us an error message or undesired result. Use System.out.println's to help you debug and narrow the problem.
From what I can guess from personal experience and other problems is that you probably ran some cd "Directory\With\Path\To\Jar" commands in command prompt when you were running it manually. You'll need to do the same for Runtime.getRuntime().exec or put the jar in the location that exec will default to in your program.
Did you try using ProcessBuilder(java.lang.ProcessBuilder)? Syntax is as follows -
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "absolute path upto jar");
Process p = pb.start();
You can redirent input/output/error to/from files as follows
File commands = new File("absolute path to inputs file");
File dirOut = new File("absolute path to outputs file");
File dirErr = new File("absolute path to error file");
dirProcess.redirectInput(commands);
dirProcess.redirectOutput(dirOut);
dirProcess.redirectError(dirErr);
I have tried it and it work! Let us know any errors or exceptions you are getting.

Execute .jar file from a Java program

How could I run a local jar file from a java program?
The jar file is not in the class-path of the Java caller program.
I suggest you 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");
pb.directory(new File("preferred/working/directory"));
Process p = pb.start();
Process proc = Runtime.getRuntime().exec("java -jar Validate.jar");
proc.waitFor();
// Then retreive the process output
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
byte b[]=new byte[in.available()];
in.read(b,0,b.length);
System.out.println(new String(b));
byte c[]=new byte[err.available()];
err.read(c,0,c.length);
System.out.println(new String(c));
First, the description of your problem is a bit unclear. I don't understand if you want to load the classes from the jar file to use in your application or the jar contains a main file you want to run. I will assume it is the second.
If so, you have a lot of options here.
The simplest one would be the following:
String filePath; //where your jar is located.
Runtime.exec(" java -jar " + filepath);
Voila...
If you don't need to run the jar file but rather load the classes out of it, let me know.
Could something like the following be useful?
http://download.oracle.com/javase/tutorial/deployment/jar/jarclassloader.html
Another way to do on windows is:
Runtime.getRuntime().exec("cmd /c start jarFile");
this way you can set priority of your process as well (normal/low/etc)
You can run a jar file from where ever you want by using only this one line code.
Desktop.getDesktop().open(new File("D:/FormsDesktop.jar"));
where
new File("your path to jar")
Hope it helps.
Thanks.
Add jar library to your project
Import main class (see manifest in jar file)
Invoke static method main with arguments
String args[] = {"-emaple","value"};
PortMapperStarter.main(args);
To run an executable jar from inside your java application, you can copy the JarClassLoader from https://docs.oracle.com/javase/tutorial/deployment/jar/examples/JarClassLoader.java
Use it like this. In this snippet, jarUrl is the URL to download the jar from, for example file:/tmp/my-jar.jar and args is the array of strings you want to pass as command line arguments to the jar.
JarClassLoader loader = new JarClassLoader(jarUrl);
String main = loader.getMainClassName();
loader.invokeClass(main, args);
Keep in mind that you're now inserting someone else's binary into your code. If it gets stuck in an infinite loop, your Thread hangs, if it calls System.exit(), your JVM exits.
This is my appriach, which I consider is more complete:
public static Process exec(String path, String filename) throws IOException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome +
File.separator + "bin" +
File.separator + "java";
ProcessBuilder pb = new ProcessBuilder(javaBin, "-jar", path+filename);
return pb.start();
}
1) Set the class path from environment variables
2) Go to the folder where your jar file exists
3) Run the following commands through command prompt
java -jar jarfilename

Runtime class in java

How to execute a java program with the help of Runtime.getRuntime().exec().
For example we shall have the java file path as c:/java/abc.java. Please help me with the code.
Assuming that abc.java contains a main method that you want to execute:
Runtime.getRuntime().exec("javac c:\java\abc.java -d c:\java\")
Runtime.getRuntime().exec("java c:\java\abc")
Do not forget that:
you may need to read stdout/stderr of a java program
you may have to set/update environment variable and PATH before executing your java command
CreateProcess: c:\j2sdk1.4.0\bin\helloworld error=2
means Win32's CreateProcess returns a 2 as error code when it cannot find the command you specify; more specifically, when the command does not refer to an executable file on its lookup path.
Look at this SO question for a more complete "Runtime.getRuntime().exec()" code, and also to this snippet.
This code creates a shell (as in Runtime.getRuntime().exec("cmd /K")), in which you write on sdtin whatever command you want to execute.
The interest of this approach is to reuse the shell process to benefit from a previous command: it you execute a 'cd', then execute a 'dir', the latter command would display the content of the directory referenced by the cd command.
The same would be true for PATH settings, just before using javac or java.
You should use ProcessBuilder instead of Runtime. Basic usage is like:
Process process = new ProcessBuilder(command).start();
You will find more code under the link above. Also see this question.
You mean you want a Java program to run another Java program. This SO thread might be helpful, in that case.
String path1 = "f://" + File.separator+username+File.separator+progName;
Runtime runtime = Runtime.getRuntime();
String command = "javac -classpath " + path + " " + path1;
System.out.println(command);
Process process = runtime.exec(command);
InputStream error = process.getErrorStream();
Please see the excellent resource which used to be called javaalmanac.
http://www.exampledepot.com/egs/java.lang/Exec.html
try {
// Execute a command with an argument that contains a space
String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"};
commands = new String[]{"grep", "hello world", "c:\\Documents and Settings\\f.txt"};
Process child = Runtime.getRuntime().exec(commands);
} catch (IOException e) {
}

Categories

Resources