Java 如何使用Graphviz从点文件格式生成PNG图像
我有一个实现优先级队列的java类。然后我有一个类测试,它生成一个如下图:Java 如何使用Graphviz从点文件格式生成PNG图像,java,queue,graphviz,Java,Queue,Graphviz,我有一个实现优先级队列的java类。然后我有一个类测试,它生成一个如下图: digraph G { Milan (0.0) -> Turin (1.2) Milan (0.0) -> Montreal (7.0) Turin (1.2) -> Paris (5.8) Turin (1.2) -> Tokyo (2.2) }
digraph G {
Milan (0.0) -> Turin (1.2)
Milan (0.0) -> Montreal (7.0)
Turin (1.2) -> Paris (5.8)
Turin (1.2) -> Tokyo (2.2)
}
此图形保存在名为“队列”的文件中
现在我希望这个图形能够用Graphviz显示在PNG图像中。
因此,我的测试文件的最后一次调用(在您创建并用优先级填充队列之后)是:
好的。toString方法如下所示:
public void toString(String fileDot){
try {
FileOutputStream file = new FileOutputStream(fileDot);
PrintStream Output = new PrintStream(file);
Output.print(this.printQueue());
Output.close();
File f = new File(fileDot);
String arg1 = f.getAbsolutePath();
String arg2 = arg1 + ".png";
String[] c = {"dot", "-Tpng", arg1, "-o", arg2};
Process p = Runtime.getRuntime().exec(c);
int err = p.waitFor();
}
catch(IOException e1) {
System.out.println(e1);
}
catch(InterruptedException e2) {
System.out.println(e2);
}
}
private String printQueue() throws IOException {
String g = new String("");
char c = '"';
g = g.concat("digraph G {\n");
if(isEmpty())
g = g.concat(" " + "Empty priority queue.");
else {
for(int i = 0; i < lastIndex; i++) {
if(heap[2 * i] != null) {
g = g.concat("" + heap[i].elem + " (" + heap[i].prior + ") " + " " + " -> " + " " + "" + heap[i * 2].elem + " (" + heap[i * 2].prior + ") \n" );
if(heap[2 * i + 1] != null)
g = g.concat("" + heap[i].elem + " (" + heap[i].prior + ") " + " " + " -> " + " " + "" + heap[i * 2 + 1].elem + " (" + heap[i * 2 + 1].prior + ") \n" );
}
} //end for
} //end else
g = g.concat("}");
return g;
}
public void toString(字符串文件点){
试一试{
FileOutputStream文件=新的FileOutputStream(fileDot);
PrintStream输出=新的PrintStream(文件);
Output.print(this.printQueue());
Output.close();
文件f=新文件(fileDot);
字符串arg1=f.getAbsolutePath();
字符串arg2=arg1+“.png”;
字符串[]c={“dot”,“-Tpng”,arg1,“-o”,arg2};
进程p=Runtime.getRuntime().exec(c);
int err=p.waitFor();
}
捕获(IOE1异常){
系统输出打印LN(e1);
}
捕捉(中断异常e2){
系统输出打印LN(e2);
}
}
私有字符串printQueue()引发IOException{
字符串g=新字符串(“”);
字符c=“”;
g=g.concat(“有向图g{\n”);
if(isEmpty())
g=g.concat(“+”空优先级队列”);
否则{
对于(int i=0;i“+”+”+“+”+heap[i*2].elem+”(“+heap[i*2].prior+”)\n);
if(堆[2*i+1]!=null)
g=g.concat(“+heap[i].elem+”(“+heap[i].prior+”)“+”+“+”->“+”+”+“+”+heap[i*2+1].elem+”(“+heap[i*2+1].prior+”)\n);
}
}//结束
}//结束其他
g=g.concat(“}”);
返回g;
}
为什么不生成image.png?我哪里错了?
当然我安装了Graphviz。
谢谢当我通过命令行上的
dot
运行上面的.dot
文件时,我得到了:
$ dot -Tpng queue.dot -oqueue.png
Warning: queue.dot:2: syntax error in line 2 near '('
因此,节点名称中的括号数字在dot
语法中无效。如果删除它们,我希望将成功创建.png
文件。如果输出中需要括号数字,我建议在GraphViz文档中查找节点标签
我还要注意的是,对于创建
.png
文件的函数来说,toString()
似乎不是一个特别清晰的名称,因此更改函数的名称可能是可取的。尝试使用点的-O
选项,而不是-O
。根据点-?
,它的作用如下:
- 根据附加了“格式”的输入文件名自动生成输出文件名。(导致忽略所有文件选项。)
所以你可以改变
String[] c = {"dot", "-Tpng", arg1, "-o", arg2};
到
非常感谢!这是错误的标签格式。再次感谢。
String[] c = {"dot", "-Tpng", arg1, "-o", arg2};
String[] c = {"dot", "-Tpng", arg1, "-O"};