0

How can I use a command line program from within Java?

I'm trying to pass a graph definition in the dot-language (see Wikipedia) to the interpreter program dot (see GraphViz) through java.

The problem is, that the program does not answer, after I have sent the dot-graph to its InputStream, because it does not know, that I'm finished sending the description.

This is, what I currently have:

package exercise4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;

public class Main {
    public static void main(String[] args) {
        PrintStream out = System.out;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        try {
            final String start =
                "strict graph LSR%1$d {\n" +
                " node [shape=circle color=lightblue style=filled];\n\n" +
                " {rank=same; A--B [label=6];}\n" +
                " {rank=same; C--D [label=12]; D--E [label=4];}\n" +
                " A--C [label=4]; B--D [label=4]; B--E [label=9];\n\n" +
                " node [shape=record color=\"#000000FF\" fillcolor=\"#00000000\"];\n}\n";
            Process dot = Runtime.getRuntime().exec("dot -Tsvg");
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintStream(dot.getOutputStream(), false, "UTF-8");
            out.printf(start, 0);

            out.flush();
            out.close();

            while(in.ready()) {
                System.out.println(in.readLine());
            }
            in.close();
            dot.destroy();
        } catch (UnsupportedEncodingException ex) {
        } catch (IOException ex) {
        } finally {
            out.close();
        }
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user1861174
  • 507
  • 1
  • 5
  • 14
  • Why do you think it doesn't know you're finished? By what mechanism is it supposed to know you are? – Marko Topolnik May 15 '13 at 11:17
  • 1- Use ProcessBuilder, it will make your life easier. 2- It's not recommended to use readLine when reading from processes, not all process will output line endings. Use Process#waitFor to get the processes exit code, which may help you diagnose the problem – MadProgrammer May 15 '13 at 11:21
  • Go through the Java World article linked from the [`exec` info. page](http://stackoverflow.com/tags/runtime.exec/info), implement **all** the recommendations, then break the args into a `String` and use a `ProcessBuilder` to create the `Process`. – Andrew Thompson May 15 '13 at 11:24

1 Answers1

0

Looks as if you are reading from the wrong input stream. Have a look at this answer: https://stackoverflow.com/a/4741987/1686330

Community
  • 1
  • 1
Dirk Lachowski
  • 3,121
  • 4
  • 40
  • 66