How to execute a batch file from java?

前端 未结 7 465
逝去的感伤
逝去的感伤 2020-12-09 20:42

I want to execute a batch file from a java program.

I am using the following command.

Runtime.getRuntime().exec(\"server.bat\");

Bu

相关标签:
7条回答
  • 2020-12-09 20:49

    You can try it with Desktop if supported (Java 1.6)

        File file = new File("server.bat");
        Desktop.getDesktop().open(file);
    
    0 讨论(0)
  • 2020-12-09 20:56

    When Java is running and you use Runtime.exec() with a relative path, relative means relative to the current user direcory, where the JVM was invoked.

    This may work

    Runtime.getRuntime().exec("cmd.exe", "/c", "./com/projct/util/server.bat");
    

    if you start java from com's parent directory.

    Or you must calculate an absolut path:

    Runtime.getRuntime().exec("cmd.exe", "/c", 
    System.getProperty("user.dir")+"/com/projct/util/server.bat");
    

    I forget, read When Runtime.exec() won't.

    0 讨论(0)
  • 2020-12-09 20:56

    The second parameter to exec is a String[] of args for the environment settings (null means inherit the process' current ones) and the third parameter to exec should be a file providing the working directory. Try this:

    Runtime.getRuntime().exec("cmd /c server.bat", null, new File("./com/project/util"));
    
    0 讨论(0)
  • 2020-12-09 21:05

    You have to run "cmd.exe" with the arguments "/c" and "server.bat":

    Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", "server.bat" } );
    
    0 讨论(0)
  • 2020-12-09 21:07

    Plexus utils provides a Commandline type that can invoke an arbitrary command line and handle parsing of the output.

    Commandline cl = new Commandline();
    
    cl.setExecutable( "cmd.exe" );
    cl.createArg().setValue( "/c" );
    
    cl.setWorkingDirectory( new File(System.getProperty("user.dir"), 
        "/com/project/util/Server.bat"));
    
    cl.createArg().setValue( "/c" );
    
    StreamConsumer consumer = new StreamConsumer() {
        public void consumeLine( String line ) {
            //do something with the line
        }
    };
    
    StreamConsumer stderr = new StreamConsumer() {
        public void consumeLine( String line ) {
            //do something with the line
        }
    };
    
    int exitCode;
    
    try {
        exitCode = CommandLineUtils.execute( cl, consumer, stderr, getLogger() );
    } catch ( CommandLineException ex ) {
        //handle exception
    }
    
    0 讨论(0)
  • 2020-12-09 21:07

    You're best bet is to store the installation directory of the application on the system and then use that to build your paths within the application. System.getProperty("user.dir") should work on Windows and Unix platforms to get the current working directory, but it is system dependent so be aware of that.

    0 讨论(0)
提交回复
热议问题