Im trying to run a jar file from java code, But unfortunately does not success.
A few details about the jar file:
The jar file located in a different folder (For example - "Folder").
The jar file using a files and folders are in the root folder (the same "Folder" i mentioned above).
What im trying to do so far:
JAR file project.
In netbeans i checked that the main class are defiend (Project properties -> Run -> Main Class).
Other JAVA program
Trying to run with the command:
Runtime.getRuntime().exec("javaw -jar "C:\\Software\\program.jar");
&&
Runtime.getRuntime().exec("javaw -jar "C:\\Software\\program.jar" "C:\\Software");
The jar file opened well, But he doesnt know and recognize his inner folders and files (the same "Folder" i mention above).
In short, it does not recognize its root folder.
Trying to run with ProcessBuilder
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "start", "javaw", "-jar", "C:\\Software\\program.jar");
pb.directory(new File("C:\\Software"));
try {
pb.start();
} catch (IOException ex) {
}
In Some PC's its works fine, But in other pc's its not work and i got an error message: "Could not find the main class"
** Offcourse if i run the jar with double click its works.
So how can i run a jar file from other java program ?
Use this variant of .exec where you specify working folder as the third argument. (In your examples, you always only use one argument.)
exec("javaw -jar "C:\\Software\\program.jar", null, "C:\\Software");
You can try to call it something like below. There are 2 types of calling it.
public class JarExecutor {
public static void main(String[] args) throws IOException, InterruptedException {
//This is first way of calling.
Process proc=Runtime.getRuntime().exec(new String[]{"java","-jar" ,"C:\\Users\\Leno\\Desktop\\JarsPractise\\JarsPrac.jar"});
//This is second way of calling.
Process proc=Runtime.getRuntime().exec(new String[]{"java","-cp","C:\\Users\\Leno\\Desktop\\JarsPractise\\JarsPrac.jar","com.shiva.practise.FloydTriangle"});
proc.waitFor();
BufferedInputStream is=new BufferedInputStream(proc.getInputStream());
byte[] byt=new byte[is.available()];
is.read(byt,0,byt.length);
System.out.println(new String(byt));
}
}
Related
I'd like to launch a jar file through an existing running Java application. I've looked into ProcessBuilder, Runtime and jproc and none of them work because they all say the same error:
CreateProcess error=193, %1 is not a valid Win32 application
The way I can get it to work is by adding the command: java -jar <path of network located jar> in any of the libraries above.
I don't want to do it this way because it messes up with location of paths and such that would run in the context of the network location if you "double clicked" the jar files directly.
Is there a way to run the jar on the network using the "default" JRE on Windows/Mac?
here is example code:
String networkLocation = "//appserver/testApp/test.jar";
// new ProcBuilder(networkLocation).withNoTimeout().run();
ProcessBuilder pb = new ProcessBuilder(networkLocation);
try
{
pb.start();
}
catch (IOException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Found out how to make the working directory using jproc:
new ProcBuilder("java", "-jar", networkLocation).withNoTimeout().withWorkingDirectory(new File ("//appserver/testApp/")).run();
And also with Runtime
Runtime.getRuntime().exec(new String[]{"java","-jar", networkLocation}, null, new File("//appserver/testApp/"));
I have a project that opens a browser with selenium. The structure looks something like this:
myProyect
src
com.open
OpenFirefox.java
lib
geckodriver
geckodriver.exe
If I make a jar file of this, I can only execute the jar if the jar in the same place as lib/geckodriver/geckodriver.exe. And both double click and java -jar firefox.jar from the console works.
Now, I need to execute this jar from another program. I have been opening other jars that have no dependencies with Desktop.getDesktop().open(file); with no problem, but when I try
try {
File file = new File("C:/Users/user/Desktop/firefox.jar");
Desktop.getDesktop().open(file);
} catch (Exception e) {
e.printStackTrace();
}
nothing happens, I dont even get an error.
What is happening?
You should use Runtime.exec()
Process process = Runtime.exec("java -jar " + filepath);
if (process.waitFor() == 0) {
System.out.println("process ran without errors");
}
private void generateDATFiles() throws Exception {
File shellScriptPath= new File((this.getClass().getResource("/Vorlagen/Simulation/test.sh").toURI()));
ProcessBuilder pb = new ProcessBuilder(shellScriptPath.getAbsolutePath());
Process p = pb.start();
}
So I have a shell script which I want to execute. The problem is that I need the file path and I can get it using getResource but I get the error that my uri is not hierarchical so I found out that I need to use getResourceAsStream to avoid the error, but my question is how I can get the file path using getResourceAsStream?
Unfortunately it won't be an easy thing to do. If you pack the .sh script together with the other part of the program in a single .jar it won't work. You can only access it as a resourcestream and not as an URI (even if in development mode you can get the actual URI). That's because the .sh AND the class files and everything is actually in the same file for the file system (.jar).
It's not so much a java limitation as the OS. If the .sh is bundled in the jar/war/any other archive you cannot run it from the java code. (Actually you cannot do it from the command prompt either).
In order to solve it you can get the input stream and write the contents in a temporary file (you can use the java createTempFile functionality) and then execute that one. Or you can extract the .sh file from the jar(zip) and execute it
Try to do with this way.
class J{
public static void main (String a[]){
{
System.out.println(J.class.getResourceAsStream("/file.txt")
}
}
I am trying to set the working directory of a process that will be running an exe.
Here is what I have so far:
public Process launchClient() throws IOException {
File pathToExecutable = new File(currentAccount.getAbsoluteFile()+"/Release", "TuringBot.exe");
System.out.println(pathToExecutable);
ProcessBuilder builder = new ProcessBuilder(pathToExecutable.getAbsolutePath());
builder.directory( new File( currentAccount, "Release" )); // this is where you set the root folder for the executable to run with
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
return builder.start();
}
but every time I launch it, the exe attempts to run but fails to because the current directory is wrong and it can't properly access the required files.
EDIT:
Here's a little more about whats going on...
I have x amount of client folders, each contains an executable file that needs to be started and relies on the contents of its local folder to execute properly, however when running this code to launch each executable file the working path for each unique executable is not being applied and is rather the default directory (the JAR's locations).
I have a Java app need to dynamically compile Java files from a src directory into a bin directory with a lib directory :
The structure looks like this :
Dir_Result
src
lib
bin
The project copies 2 directories src and lib from Dir_Origin to Dir_Result, it then programmatically changes some Java files in the Dir_Result/src and compiles them into Dir_Result/bin
Usually I use Netbeans to compiles projects, but now I need to write Java code to do the compiling for me. I've tried the following approach, it went through without error. Yet I don't see anything in the bin directory. No errors and no output.
runCommand("javac -d C:/Dir_Result/bin/ -cp C:/Dir_Result/lib/* C:/Dir_Result/src/*");
...
public static String runCommand(String Command)
{
String Line,Result="";
Process Child;
try
{
Child=Runtime.getRuntime().exec("cmd.exe /c "+Command);
Result+="Executing : "+Command+"\n";
BufferedReader Input=new BufferedReader(new InputStreamReader(Child.getInputStream()));
while ((Line=Input.readLine()) != null) Result+=Line+"\n";
Input.close();
Result+="Done\n";
}
catch (IOException e) { Result+=e.toString(); }
return Result;
}
I'm not sure what went wrong, how to fix it ? If I need to setup classpath, how to do it within my program, or is it doable from runCommand ?
I found out why, it's because some of my Java files has some characters in a different encoding, so I added "-encoding ISO-8859-1" and it worked.