简体   繁体   中英

How can i run a .jar file in java

I'm making an update function for my project, it's working great, until i want it to restart, basically I download the new file and replace it with the old one, and then i want to run it again, now for some reason it doesn't wna run, and i don't get any error...

Here is the complete update class: http://dl.dropbox.com/u/38414202/Update.txt

Here is the method i'm using to run my .jar file:

 String currDir = new File("(CoN).jar").getAbsolutePath();
 Process runManager = Runtime.getRuntime().exec("java -jar " + currDir);

It's not clear to me, why do you need to run the jar with a call to exec() . Given that you need to run the code in the .jar file from a Java program, you could simply run the main() method as defined in the jar's manifest, and capture its output - wherever that is.

Using exec() is OK when you need to call a program from the underlying operating system, but there are easier ways to do this if both the caller and the callee are Java programs.

Now, if your jar is gonna change dynamically and you need to update your program according to a new jar, there are mechanisms for reloading its contents, for instance take a look ath this other post .

The JavaDocs for the Process class specifically point out that if you don't capture the output stream of the Process and promptly read it that the process could halt. If this is the case, then you wouldn't see the process that you started run.

I think you have to capture the stream like this :

BufferedReader stdInput = new BufferedReader(new InputStreamReader(runManager.getInputStream()),8*1024);

BufferedReader stdError = new BufferedReader(new InputStreamReader(runManager.getErrorStream()));

// read the output from the command

String s = null;
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
    }

The exec function doesn't automatically lookup into the PATH to start a process, so you have to pass the complete path for the java binary.

You can do that by using the java.home system property, see this answer: ProcessBuilder - Start another process / JVM - HowTo?

No one here seemed to help me, so I went to ask my friend and I had it almost right. It abiously required the string to be an array.

solution:

String[] cmd = {"java", "-jar", currDir};
try {
  Runtime.getRuntime().exec(cmd);
} catch (IOException e1) {
  e1.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM