Running other programs from Java

耗尽温柔 提交于 2019-11-29 16:18:37
wheaties

Here:

ProcessBuilder processbuilder
try 
{
    processbuilder.directory(file);
    processbuilder.redirectErrorStream(true);

    process = processbuilder.start();

    String readLine;
    BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
    // include this too: 
    // BufferedReader output = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    while((readLine = output.readLine()) != null)
    {
        m_Logger.info(readLine);
    }

    process.waitFor();
}

I've used something similar. You'll actually want to do something with the readLine. I just copied and pasted from code where I didn't care what it said.

Brian Agnew

The redirection > (like the pipe |) is a shell construct and only works when you execute stuff via /bin/sh (or equivalent). So the above isn't really going to work. You could execute

/bin/sh -c "svn log --xml -v > svn.log"

and read svn.log.

Alternatively, you can read the output from the process execution and dump that to a file (if you need to dump it to a file, or just consume it directly as you read it). If you choose this route and consume stdout/stderr separately, note that when you consume the output (stdout), you need to consume stderr as well, and concurrently, otherwise buffers will block (and your spawned process) waiting for your process to consume this. See this answer for more details.

instead of piping in your command, just let it print to standard output and error output. You can access those streams from your process object that is returned from exec.

For the svn stuff use java SVNKit API.

Seeing your two commands, why don't you do it directly from Java, without executing ? You could use SVNKit for the svn part, and include directly the jars in your classpath.

Try this

public static void main(String[] args) {
        try {
            // Execute a command with an argument that contains a space
            System.out.println(args[0]);
            String[]commands = new String[]{"svn", "info", args[0]};
            Process process = Runtime.getRuntime().exec(commands);
            BufferedReader reader =  new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
            }
            String result = builder.toString();
            System.out.println(result);

        }catch(Exception e){
            System.out.print(e);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!