how to redirect stdin to java Runtime.exec?

前端 未结 2 1509
失恋的感觉
失恋的感觉 2020-12-18 06:27

I want to execute some sql scripts using Java\'s Runtime.exec method. I intend to invoke mysql.exe / mysql.sh and redirect the script file to this process. From the command

2条回答
  •  佛祖请我去吃肉
    2020-12-18 06:55

    Redirection is a functionality of the OS shell/cmd enviroments. To invoke them correctly we should use Runtime.exec(String[]) instead of Runtime.exec(String). Here is the code.

    public Result executeCmd(String[] cmds, boolean waitForResult)
    {
        Result result = new Result();
        result.output = "";
        try
        {
            for(int i=0;i 1)
                process=Runtime.getRuntime().exec(cmds);
            else
                process=Runtime.getRuntime().exec(cmds[0]);
            if (waitForResult)
            {
                StreamGobbler errordataReader = new StreamGobbler(process
                        .getErrorStream(), "ERROR");
    
                StreamGobbler outputdataReader = new StreamGobbler(process
                        .getInputStream(), "OUTPUT");
    
                errordataReader.start();
                outputdataReader.start();
    
                int exitVal = process.waitFor();
                errordataReader.join();
                outputdataReader.join();
                result.returnCode = exitVal;
                result.output = outputdataReader.output;
                result.error = errordataReader.output;
            }
        }
        catch (Exception exp)
        {
            result.exp = exp;
            result.returnCode = -1;
        }
        return result;
    }
    

    And call this method using

    Result result = executeCmd(cmds, true);
    

    where

    CMD[0]::cmd
    CMD[1]::/c
    CMD[2]::.\mysql\bin\mysql --host= --port= -u   < .\scripts\create_tables.sql
    

提交回复
热议问题