栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从Java调用GraphViz

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从Java调用GraphViz

检查此
API,它很简单,并且具有几种输出格式(即pdf gif ..etc)。

编辑2016年5月: 许多人评论说该API不再可用;这里是其源代码:

首先

config.properties
,您需要创建并复制以下文件,然后粘贴以下文件:

###############################################################         Linux Configurations         ################################################################ The dir. where temporary files will be created.tempDirForLinux = /tmp# Where is your dot program located? It will be called externally.dotForLinux = /usr/bin/dot###############################################################        Windows Configurations        ################################################################ The dir. where temporary files will be created.tempDirForWindows = c:/temp# Where is your dot program located? It will be called externally.dotForWindows = "c:/Program Files (x86)/Graphviz 2.28/bin/dot.exe"###############################################################         Mac Configurations################################################################ The dir. where temporary files will be created.tempDirForMacOSX = /tmp# Where is your dot program located? It will be called externally.dotForMacOSX = /usr/local/bin/dot

然后是Graphviz.java源代码

// GraphViz.java - a simple API to call dot from Java programsimport java.io.BufferedReader;import java.io.BufferedWriter;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.InputStreamReader;import java.util.Properties;public class GraphViz{        private final static String osName = System.getProperty("os.name").replaceAll("\s","");        private final static String cfgProp = "/Users/seteropere/NetBeansProjects/TestApplication/src/config.properties";    private final static Properties configFile = new Properties() {        private final static long serialVersionUID = 1L; { try {     load(new FileInputStream(cfgProp)); } catch (Exception e) {}        }    };      private static String TEMP_DIR = "/Users/seteropere/NetBeansProjects/TestApplication";      private static String DOT = configFile.getProperty("dotFor" + osName);        private int[] dpiSizes = {46, 51, 57, 63, 70, 78, 86, 96, 106, 116, 128, 141, 155, 170, 187, 206, 226, 249};        private int currentDpiPos = 7;        public void increaseDpi() {        if ( this.currentDpiPos < (this.dpiSizes.length - 1) ) { ++this.currentDpiPos;        }    }        public void decreaseDpi() {        if (this.currentDpiPos > 0) { --this.currentDpiPos;        }    }    public int getImageDpi() {        return this.dpiSizes[this.currentDpiPos];    }        private StringBuilder graph = new StringBuilder();        public GraphViz() {    }        public String getDotSource() {        return this.graph.toString();    }        public void add(String line) {        this.graph.append(line);    }        public void addln(String line) {        this.graph.append(line + "n");    }        public void addln() {        this.graph.append('n');    }    public void clearGraph(){        this.graph = new StringBuilder();    }        public byte[] getGraph(String dot_source, String type)    {        File dot;        byte[] img_stream = null;        try { dot = writeDotSourceToFile(dot_source); if (dot != null) {     img_stream = get_img_stream(dot, type);     if (dot.delete() == false)          System.err.println("Warning: " + dot.getAbsolutePath() + " could not be deleted!");     return img_stream; } return null;        } catch (java.io.IOException ioe) { return null; }    }        public int writeGraphToFile(byte[] img, String file)    {        File to = new File(file);        return writeGraphToFile(img, to);    }        public int writeGraphToFile(byte[] img, File to)    {        try { FileOutputStream fos = new FileOutputStream(to); fos.write(img); fos.close();        } catch (java.io.IOException ioe) { return -1; }        return 1;    }        private byte[] get_img_stream(File dot, String type)    {        File img;        byte[] img_stream = null;        try { img = File.createTempFile("graph_", "."+type, new File(GraphViz.TEMP_DIR)); Runtime rt = Runtime.getRuntime(); // patch by Mike Chenault String[] args = {DOT, "-T"+type, "-Gdpi="+dpiSizes[this.currentDpiPos], dot.getAbsolutePath(), "-o", img.getAbsolutePath()}; Process p = rt.exec(args); p.waitFor(); FileInputStream in = new FileInputStream(img.getAbsolutePath()); img_stream = new byte[in.available()]; in.read(img_stream); // Close it if we need to if( in != null ) in.close(); if (img.delete() == false)      System.err.println("Warning: " + img.getAbsolutePath() + " could not be deleted!");        }        catch (java.io.IOException ioe) { System.err.println("Error:    in I/O processing of tempfile in dir " + GraphViz.TEMP_DIR+"n"); System.err.println("       or in calling external command"); ioe.printStackTrace();        }        catch (java.lang.InterruptedException ie) { System.err.println("Error: the execution of the external program was interrupted"); ie.printStackTrace();        }        return img_stream;    }        private File writeDotSourceToFile(String str) throws java.io.IOException    {        File temp;        try { temp = File.createTempFile("dorrr",".dot", new File(GraphViz.TEMP_DIR)); FileWriter fout = new FileWriter(temp); fout.write(str); BufferedWriter br=new BufferedWriter(new FileWriter("dotsource.dot")); br.write(str); br.flush(); br.close(); fout.close();        }        catch (Exception e) { System.err.println("Error: I/O error while writing the dot source to temp file!"); return null;        }        return temp;    }        public String start_graph() {        return "digraph G {";    }        public String end_graph() {        return "}";    }        public String start_subgraph(int clusterid) {        return "subgraph cluster_" + clusterid + " {";    }        public String end_subgraph() {        return "}";    }        public void readSource(String input)    {        StringBuilder sb = new StringBuilder();        try        { FileInputStream fis = new FileInputStream(input); DataInputStream dis = new DataInputStream(fis); BufferedReader br = new BufferedReader(new InputStreamReader(dis)); String line; while ((line = br.readLine()) != null) {     sb.append(line); } dis.close();        }         catch (Exception e) { System.err.println("Error: " + e.getMessage());        }        this.graph = sb;    }} // end of class GraphViz

一个例子是:

public static void createDotGraph(String dotFormat,String fileName){    GraphViz gv=new GraphViz();    gv.addln(gv.start_graph());    gv.add(dotFormat);    gv.addln(gv.end_graph());   // String type = "gif";    String type = "pdf";  // gv.increaseDpi();    gv.decreaseDpi();    gv.decreaseDpi();    File out = new File(fileName+"."+ type);     gv.writeGraphToFile( gv.getGraph( gv.getDotSource(), type ), out );}

像这样调用它:

    public static void main(String[] args) throws Exception {        String dotFormat="1->2;1->3;1->4;4->5;4->6;6->7;5->7;3->8;3->6;8->7;2->8;2->5;";        createDotGraph(dotFormat, "DotGraph"); }

它将在您指定的目录中创建

dotsource.dot
DotGraph.pdf
表示一个立方图。请记住:您只需要更改代码中两个参数的值:
cfgProp
TEMP_DIR

希望能有所帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/440987.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号