views:

108

answers:

5

Hello,

I need to run a couple of other programs from my own Java program, basically I need to run these command line statements.

svn log --xml -v > svn.log

and

java -jar example.jar arg1 arg2

and I need to use the text outputs written to the console from these programs in my own program. I've tried Runtime.getRuntime().exec() with the svn, but it doesn't seem to be doing anything because it doesn't make a svn.log file. Also both programs need to be called in different places, the svn line needs to be called from inside one folder and the java line needs to be called from another.

Any ideas on how to go about this? If this is not possible in Java, is there a way to do it in C#?

Thanks

+3  A: 

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.

wheaties
A: 

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.

+3  A: 

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.

Brian Agnew
+1 for the ">" this is a common source of problems ( as well as variable expansion )
OscarRyz
A: 

For the svn stuff use java SVNKit API.

emeraldjava
A: 

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.

Valentin Rocher