Java:使用第三方库GraphViz画图TEST

Wesley13
• 阅读 654

一.在eclipse中使用Graphviz:建立一个 class Graphviz

GraphViz库的代码如下(复制到class GraphViz中)

//GraphViz.java - a simple API to call dot from Java programs
/*$Id$*/
/*
******************************************************************************
*                                                                            *
*              (c) Copyright 2003 Laszlo Szathmary                           *
*                                                                            *
* This program is free software; you can redistribute it and/or modify it    *
* under the terms of the GNU Lesser General Public License as published by   *
* the Free Software Foundation; either version 2.1 of the License, or        *
* (at your option) any later version.                                        *
*                                                                            *
* This program is distributed in the hope that it will be useful, but        *
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *
* or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public    *
* License for more details.                                                  *
*                                                                            *
* You should have received a copy of the GNU Lesser General Public License   *
* along with this program; if not, write to the Free Software Foundation,    *
* Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                              *
*                                                                            *
******************************************************************************
*/

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;

/**
* <dl>
* <dt>Purpose: GraphViz Java API
* <dd>
*
* <dt>Description:
* <dd> With this Java class you can simply call dot
*      from your Java programs
* <dt>Example usage:
* <dd>
* <pre>
*    GraphViz gv = new GraphViz();
*    gv.addln(gv.start_graph());
*    gv.addln("A -> B;");
*    gv.addln("A -> C;");
*    gv.addln(gv.end_graph());
*    System.out.println(gv.getDotSource());
*
*    String type = "gif";
*    File out = new File("out." + type);   // out.gif in this example
*    gv.writeGraphToFile( gv.getGraph( gv.getDotSource(), type ), out );
* </pre>
* </dd>
*
* </dl>
*
* @version v0.4, 2011/02/05 (February) -- Patch of Keheliya Gallaba is added. Now you
* can specify the type of the output file: gif, dot, fig, pdf, ps, svg, png, etc.
* @version v0.3, 2010/11/29 (November) -- Windows support + ability 
* to read the graph from a text file
* @version v0.2, 2010/07/22 (July) -- bug fix
* @version v0.1, 2003/12/04 (December) -- first release
* @author  Laszlo Szathmary (<a href="jabba.laci@gmail.com">jabba.laci@gmail.com</a>)
*/
public class Graphviz
{
/**
 * The dir. where temporary files will be created.
 */
//private static String TEMP_DIR = "/tmp"; // Linux
private static String TEMP_DIR = "c:/temp"; // Windows

/**
 * Where is your dot program located? It will be called externally.
 */
// private static String DOT = "/usr/bin/dot"; // Linux
private static String DOT = "C:\\Program Files (x86)\\Graphviz2.38\\bin\\dot.exe"; // Windows

/**
 * The source of the graph written in dot language.
 */
private StringBuilder graph = new StringBuilder();

/**
 * Constructor: creates a new GraphViz object that will contain
 * a graph.
 */
public Graphviz() {
}

/**
 * Returns the graph's source description in dot language.
 * @return Source of the graph in dot language.
 */
public String getDotSource() {
   return graph.toString();
}

/**
 * Adds a string to the graph's source (without newline).
 */
public void add(String line) {
   graph.append(line);
}

/**
 * Adds a string to the graph's source (with newline).
 */
public void addln(String line) {
   graph.append(line + "\n");
}

/**
 * Adds a newline to the graph's source.
 */
public void addln() {
   graph.append('\n');
}

/**
 * Returns the graph as an image in binary format.
 * @param dot_source Source of the graph to be drawn.
 * @param type Type of the output image to be produced, e.g.: gif, dot, fig, pdf, ps, svg, png.
 * @return A byte array containing the image of the graph.
 */
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; }
}

/**
 * Writes the graph's image in a file.
 * @param img   A byte array containing the image of the graph.
 * @param file  Name of the file to where we want to write.
 * @return Success: 1, Failure: -1
 */
public int writeGraphToFile(byte[] img, String file)
{
   File to = new File(file);
   return writeGraphToFile(img, to);
}

/**
 * Writes the graph's image in a file.
 * @param img   A byte array containing the image of the graph.
 * @param to    A File object to where we want to write.
 * @return Success: 1, Failure: -1
 */
public int writeGraphToFile(byte[] img, File to)
{
   try {
      FileOutputStream fos = new FileOutputStream(to);
      fos.write(img);
      fos.close();
   } catch (java.io.IOException ioe) { ioe.printStackTrace();return -1; }
   return 1;
}

/**
 * It will call the external dot program, and return the image in
 * binary format.
 * @param dot Source of the graph (in dot language).
 * @param type Type of the output image to be produced, e.g.: gif, dot, fig, pdf, ps, svg, png.
 * @return The image of the graph in .gif format.
 */
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, 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;   }
/**
 * Writes the source of the graph in a file, and returns the written file
 * as a File object.
 * @param str Source of the graph (in dot language).
 * @return The file (as a File object) that contains the source of the graph.
 */
public File writeDotSourceToFile(String str) throws java.io.IOException
{
   File temp;
   try {
      temp = File.createTempFile("graph_", ".dot.tmp", new File(Graphviz.TEMP_DIR));
      FileWriter fout = new FileWriter(temp);
      fout.write(str);
      fout.close();
   }
   catch (Exception e) {
      System.err.println("Error: I/O error while writing the dot source to temp file!");
      return null;
   }
   return temp;
}

/**
 * Returns a string that is used to start a graph.
 * @return A string to open a graph.
 */
public String start_graph() {
   return "digraph G {" ;
}

/**
 * Returns a string that is used to end a graph.
 * @return A string to close a graph.
 */
public String end_graph() {
   return "}";
}

/**
 * Read a DOT graph from a text file.
 * 
 * @param input Input text file containing the DOT graph
 * source.
 */
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

二.使用GraphViz库画图,GraphViz画图代码示例见https://www.2cto.com/kf/201212/173431.html

测试代码如下:

import java.io.File;

public class GTest {
    public static void main(String[] args){
        GTest gtest = new GTest();
        String[] nodes = {"A","B","C","D","E","F","G"};
        String[] preline = {"B -> A","D -> B","E -> D","C -> E","G -> C","F -> G"};
        gtest.start(nodes, preline);
    }
    private void start(String[] nodes,String[] preline){
           
           Graphviz gv = new Graphviz();
           //定义每个节点的style
           String nodesty = "[shape = polygon, sides = 6, peripheries = 2, color = lightblue, style = filled]";
           //String linesty = "[dir=\"none\"]";
           
           gv.addln(gv.start_graph());//SATRT
           gv.addln("edge[fontname=\"DFKai-SB\" fontsize=15 fontcolor=\"black\" color=\"brown\" style=\"filled\"]");
           gv.addln("size =\"8,8\";");
           //设置节点的style
           for(int i=0;i<nodes.length;i++){
               gv.addln(nodes[i]+" "+nodesty);
           }
           for(int i=0;i<preline.length;i++){
               gv.addln(preline[i]+" "+" [dir=\"none\"]");
           }
           gv.addln(gv.end_graph());//END
           //节点之间的连接关系输出到控制台
           System.out.println(gv.getDotSource());
           //输出什么格式的图片(gif,dot,fig,pdf,ps,svg,png,plain)
           String type = "png";
           //输出到文件夹以及命名
           File out = new File("C:/Users/fanghui/Desktop/GraphTest/test." + type);   // Linux
           //File out = new File("c:/eclipse.ws/graphviz-java-api/out." + type);    // Windows
           gv.writeGraphToFile( gv.getGraph( gv.getDotSource(), type ), out );
       }
}

三.结果:

控制台输出

 Java:使用第三方库GraphViz画图TEST

输出生成的图片

Java:使用第三方库GraphViz画图TEST

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这