2014-02-17 39 views
3

我想使用GraphViz在我的程序中生成一些图形。这只是一个问题:我不想生成任何临时文件。使用Java创建GraphViz图形,无需任何中间文件

以下是我从这里得到:

public class GraphBuilder{ 
    /* Some code generating a DOT formatted String representing my graph */ 

    /* Generation the graph using the plain format */ 
    Runtime runtime = Runtime.getRuntime(); 
    Process p = null; 
    try { 
     p = runtime.exec("neato -Tplain c:\\users\\tristan\\desktop\\test1"); 
    } catch (IOException e) { 
     System.err.println(e.getMessage()); 
    } 

    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); 
    StringBuilder builder = new StringBuilder(); 
    String line = null; 
    try{ 
     while ((line = br.readLine()) != null) { 
      builder.append(line); 
      builder.append(System.getProperty("line.separator")); 
     } 
    } catch(IOException e){ 

    } 
    String result = builder.toString(); 
    System.out.println(result); 

确定,所以,从现在开始,我的程序读取一个文件,但我想要的NEATO程序读取早些时候由程序生成我的字符串。

我该怎么办?

在此先感谢!

+0

你已经搜索的Java API在这里吧? http://www.graphviz.org/Resources.php – Leo

+0

是的,但似乎每个Java API使用临时文件 – Kaijiro

+0

这是一个耻辱。 :-(如果它们中的任何一个是开源的,也许你可以使用它来使用流,而不是写入磁盘。对不起,没有更好的建议:-( – Leo

回答

5

喜欢的东西:

// Create the process 
Process process = new ProcessBuilder("neato", "-Tplain").start(); 

// Write to process's stdin 
OutputStream osToProcess = process.getOutputStream(); 
PrintWriter pwToProcess = new PrintWriter(osToProcess); 
pwToProcess.write("graph G { node1 -- node2; }"); // for example 
pwToProcess.close(); 

// Read from process's stdout 
InputStream isFromProcess = process.getInputStream(); 
BufferedReader brFromProcess = new BufferedReader(isFromProcess); 
// do whatever you want with the reader, then... 
brFromProcess.close(); 

// optionally... 
process.waitFor(); 

我省略例外从这个例子代码处理 - 你需要把它放在满足您的要求。将所有东西包装在try/catch块中可能就足够了 - 这取决于你需要的东西。

我验证了neato读取在命令行中/写标准输入/输出:

$ echo 'graph G { n1 -- n2; }' | neato -Tplain 
graph 1 1.3667 1.2872 
node n1 0.375 0.25 0.75 0.5 n1 solid ellipse black lightgrey 
node n2 0.99169 1.0372 0.75 0.5 n2 solid ellipse black lightgrey 
edge n1 n2 4 0.55007 0.47348 0.63268 0.57893 0.7311 0.70457 0.81404 0.81044 solid black 
stop 
+0

本来使用的是Runtime.exec()。ProcessBuilder从Java 1.5开始推荐使用。 – slim

+0

Dude你真是太棒了!非常感谢!!!! * windows用户注意事项:删除图形声明周围的引号。* – Kaijiro