GraphViz的使用及其中文字符的繪製

GraphViz爲繪製有向網絡的可視化工具包

使用方法如下:

1)下載安裝http://www.graphviz.org/Download..php。此處說明皆以Windows版本爲平臺。

2)在Java項目中新建類GraphViz,代碼如下,其中需要改的有兩處:一處是TEMP_DIR變量的取值,選擇自己需要保存文件的路徑;二是DOT變量的取值,應該爲安裝GraphViz後路徑中的dot程序文件路徑(此處爲2.30版本默認路徑)

import 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.io.OutputStreamWriter;


public class GraphViz {
        private static String TEMP_DIR = "c:/temp";
        private static String DOT = "C:\\Program Files\\Graphviz2.30\\bin\\dot.exe";
        private StringBuilder graph = new StringBuilder();


        public GraphViz() {
        }


        public String getDotSource() {
                return graph.toString();
        }


        public void add(String line) {
                graph.append(line);
        }


        public void addln(String line) {
                graph.append(line + "\n");
        }


        public void addln() {
                graph.append('\n');
        }


        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();
                        String[] args = { DOT, "-T" + type, 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);
                        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("graph_", ".dot.tmp", new File(
                                        GraphViz.TEMP_DIR));
                        FileOutputStream fos=new FileOutputStream(temp.getAbsolutePath());
                        BufferedWriter br=new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
                        br.write(str);
                        br.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 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;
        }
}


3)測試使用代碼:

import java.io.File;


public class Proba {
        public static void main(String[] args) {
                Proba p = new Proba();
                p.start();
                // p.start2();
        }


        private void start() {
                GraphViz gv = new GraphViz();
                gv.addln(gv.start_graph());
                gv.addln("rankdir = LR");
                gv.addln("encoding=\"UTF-8\"");
                gv.addln("node [shape=box,fontname=\"simhei.ttf\",style=filled, fillcolor=\".7 .3 1.0\", color=green, fontsize=10]");
                gv.addln("edge[arrowsize= 1.5, arrowhead=\"open\",fontsize=10]");
                gv.addln("A -> D->黑體[penwidth=7,color=\"red\"];");
                gv.addln("A -> C;");
                gv.addln("計算機->C->B;");
                gv.addln(gv.end_graph());
                System.out.println(gv.getDotSource());


                String type = "gif";
                // String type = "dot";
                // String type = "fig"; // open with xfig
                // String type = "pdf";
                // String type = "ps";
                // String type = "svg"; // open with inkscape
                // String type = "png";
                // String type = "plain";
                File out = new File("c:\\temp\\out." + type);
                gv.writeGraphToFile(gv.getGraph(gv.getDotSource(), type), out);
        }


        private void start2() {
                String input = "c:/temp/simple.txt";
                GraphViz gv = new GraphViz();
                gv.readSource(input);
                System.out.println(gv.getDotSource());


                String type = "gif";
                // String type = "dot";
                // String type = "fig"; // open with xfig
                // String type = "pdf";
                // String type = "ps";
                // String type = "svg"; // open with inkscape
                // String type = "png";
                // String type = "plain";
                File out = new File("c:/temp/out." + type);
                gv.writeGraphToFile(gv.getGraph(gv.getDotSource(), type), out);
        }
}


運行界面爲:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章