简体   繁体   中英

How can I run a jar file?

I searched long to find code to run a jar file, but this is the only code I found:

public class Main {
    
    public static void main (String args[]) {
        try {
            Runtime.getRuntime().exec("java -jar C:/Users/lordb/Desktop/Server/NewBuildTest/spigot-1.18.1.jar");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

but it didn't work. Just nothing happens. No Exception, no Error, nothing. Can someone help me?

There is at least one cause, because there is no single command with the name

"java -jar C:/Users/lordb/Desktop/Server/NewBuildTest/spigot-1.18.1.jar"

What you want, is to execte the command "java" with the 2 arguments "-jar" and "C:/Users/lordb/Desktop/Server/NewBuildTest/spigot-1.18.1.jar". You can do that by passing the command and its arguments via String array. In your case that would be an array of 3 Strings.

Javadoc: https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String[])

In that javadoc you can see that exec returns a new Process object. Such Process provides more information, eg the exit code of your process (via waitFor ) and access to (error) output messages (via getInputStream ).

Javadoc: https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html

Example: Printing a Java InputStream from a Process

Note: You didn't specify which Java version you are using, so i just picked a "random" version for the javadoc links. You might need to look for the version you are using.

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