Running JAR file on Windows

前端 未结 25 2017
故里飘歌
故里飘歌 2020-11-22 01:57

I have a JAR file named helloworld.jar. In order to run it, I\'m executing the following command in a command-line window:



        
25条回答
  •  有刺的猬
    2020-11-22 02:46

    Actually, I faced this problem too, I got around with it by making a .bat runner for my jar file

    here is the code:

    class FileHandler{
       public static File create_CMD_Rnner(){
          int exitCode = -1625348952;
          try{
               File runner = new File(Main.batName);
               PrintWriter printer = new PrintWriter(runner);
               printer.println("@echo off");
               printer.println("title " + Main.applicationTitle);
               printer.println("java -jar " + Main.jarName + " " + Main.startCode );
               printer.println("PAUSE");
               printer.flush();
               printer.close();
               return runner;
           }catch(Exception e){
               System.err.println("Coudln't create a runner bat \n exit code: " + exitCode);
               System.exit(exitCode);
               return null;
           }
       }
    }
    



    Then in Your Main application class do this:

    public class Main{
        static String jarName = "application.jar";
        static String applicationTitle = "java Application";
        static String startCode = "javaIsTheBest";
        static String batName = "_.bat";
    
    
        public static void main(String args[]) throws Exception{
            if(args.length == 0 || !args[0].equals(startCode)) {
                Desktop.getDesktop().open(FilesHandler.create_CMD_Rnner());
                System.exit(0);
            }else{
                //just in case you wanted to hide the bat
                deleteRunner();
                // Congratulations now you are running in a cmd window ... do whatever you want
                //......
                System.out.println("i Am Running in CMD");
                //......
                Thread.sleep(84600);
            }
        }
    
    
        public static void deleteRunner(){
            File batRunner = new File(batName);
            if(batRunner.exists()) batRunner.delete();
        }
    }
    


    Please Note that

    1. this code (my code) works only with a jar file, not a class file.

    2. the jar file must have the same name as the String "jarName" is the Main class

提交回复
热议问题