How to execute a batch file from java?

前端 未结 7 480
逝去的感伤
逝去的感伤 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 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
    }
    

提交回复
热议问题