简体   繁体   中英

Make a Java application run itself from the command prompt?

I have an executable Jar file and to keep it simple, I want to make it so that you can simply double click it on the desktop and it will run. I've tried this:

if(args.length == 0){
        String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String decodedPath = URLDecoder.decode(path, "UTF-8");
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("java -jar \"" + decodedPath + "\" -arg");
        System.out.println("java -jar \"" + decodedPath + "\" -arg");
    }

To no avail. I assumed that if I told the program to check for the "-arg" argument and it wasn't there, then it would asssume the program was run from the executable, not being called from the command line. So is there a way to make the program open a command prompt and then run itself within it, killing the previous program?

As to "run on double click", this is OS dependent.

You can "run a jar" at the command line using:

java -jar the.jar

This requires that the jar has a META-INF/MANIFEST.MF and that this manifest file has a Main-Class entry, the argument being the class where your main() method is. For instance:

Main-Class: org.foobar.mypackage.Foo

What I have done for a similar problem is that I have made a separate GUI program in a JAR file with some JTextField s for input and a JButton for confirmation. When the button gets clicked, it calls the main method in my other class with those values in a String array to start that program and close the GUI form with frame.setVisible(false) . I suggest doing something like that, but it's dependent on what type of program you're developing.

You could also just pass the necessary command-line flags directly into the JRE at runtime ! I just figured this out a couple weeks ago, but you can access the java.library.path and change it to match necessary library paths through reflection by just putting this code in the front of your main method.

try{
    System.setProperty("java.library.path", path);
    Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
    fieldSysPath.setAccessible( true );
    fieldSysPath.set( null, null );
}catch(Exception ex){
    // just exit and tell user that there was an error or something similar
}

Anyway, I hope that this was helpful. You can also do many similar things by similar code.

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