java -- java中调用GraphViz

2024-03-29 06:48
文章标签 java 调用 graphviz

本文主要是介绍java -- java中调用GraphViz,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

java – java中调用GraphViz

1.相关的代码

摘自:http://stackoverflow.com/questions/26481910/how-to-call-graphviz-from-java

一些前提知识:

  • 利用GraphViz的命令行,在命令行窗口中使用。(dot -Tgif -o output.gif test2.dot

下面编程中用到的一些技巧。

  1. 配置文件的使用。(通过Properties加载配置文件
  2. 动态调用其他的进程。(通过Runtime来实现)
  3. 临时文件的使用。(public static File createTempFile(String prefix,
    String suffix)在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。【临时目录必须提前存在,而不是此方法创建】

1.1为GraphViz的java的API建立一个config.properties。


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.
tempDirForWindows7 = E:/temp
# Where is your dot program located? It will be called externally.
dotForWindows7 = "E:/software_daily/FOR_LEARN/graphViz/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

1.2 针对GraphViz写的API。(简单版本)

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.util.Properties;/**
* <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.5.1, 2013/03/18 (March) -- Patch of Juan Hoyos (Mac support)
* @version v0.5, 2012/04/24 (April) -- Patch of Abdur Rahman (OS detection + start subgraph + 
* read config file)
* @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
{/*** Detects the client's operating system.*/private final static String osName = System.getProperty("os.name").replaceAll("\\s","");/*** Load the config.properties file.*/private final static String cfgProp = "config/config.properties";private final static Properties configFile = new Properties() {private final static long serialVersionUID = 1L; {try {load(new FileInputStream(cfgProp));} catch (Exception e) {}}};/*** The dir. where temporary files will be created.*/
private static String TEMP_DIR = "test/tmpDir";/*** Where is your dot program located? It will be called externally.*/
private static String DOT = configFile.getProperty("dotFor" + osName);/*** The image size in dpi. 96 dpi is normal size. Higher values are 10% higher each.* Lower values 10% lower each.* * dpi patch by Peter Mueller*/private int[] dpiSizes = {46, 51, 57, 63, 70, 78, 86, 96, 106, 116, 128, 141, 155, 170, 187, 206, 226, 249};/*** Define the index in the image size array.*/private int currentDpiPos = 7;/*** Increase the image size (dpi).*/public void increaseDpi() {if ( this.currentDpiPos < (this.dpiSizes.length - 1) ) {++this.currentDpiPos;}}/*** Decrease the image size (dpi).*/public void decreaseDpi() {if (this.currentDpiPos > 0) {--this.currentDpiPos;}}public int getImageDpi() {return this.dpiSizes[this.currentDpiPos];}/*** 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 this.graph.toString();}/*** Adds a string to the graph's source (without newline).*/public void add(String line) {this.graph.append(line);}/*** Adds a string to the graph's source (with newline).*/public void addln(String line) {this.graph.append(line + "\n");}/*** Adds a newline to the graph's source.*/public void addln() {this.graph.append('\n');}public void clearGraph(){this.graph = new StringBuilder();}/*** 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) { 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 ChenaultString[] 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 toif( 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.*/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;}/*** 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 "}";}/*** Takes the cluster or subgraph id as input parameter and returns a string* that is used to start a subgraph.* @return A string to open a subgraph.*/public String start_subgraph(int clusterid) {return "subgraph cluster_" + clusterid + " {";}/*** Returns a string that is used to end a graph.* @return A string to close a graph.*/public String end_subgraph() {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;}

1.3使用示例

下面这个为主要测试情况:

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 );
}

我们在main函数中调用上面的方法:

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");}

这篇关于java -- java中调用GraphViz的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/857895

相关文章

Spring Boot循环依赖原理、解决方案与最佳实践(全解析)

《SpringBoot循环依赖原理、解决方案与最佳实践(全解析)》循环依赖指两个或多个Bean相互直接或间接引用,形成闭环依赖关系,:本文主要介绍SpringBoot循环依赖原理、解决方案与最... 目录一、循环依赖的本质与危害1.1 什么是循环依赖?1.2 核心危害二、Spring的三级缓存机制2.1 三

在Spring Boot中浅尝内存泄漏的实战记录

《在SpringBoot中浅尝内存泄漏的实战记录》本文给大家分享在SpringBoot中浅尝内存泄漏的实战记录,结合实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录使用静态集合持有对象引用,阻止GC回收关键点:可执行代码:验证:1,运行程序(启动时添加JVM参数限制堆大小):2,访问 htt

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

浅析Java中如何优雅地处理null值

《浅析Java中如何优雅地处理null值》这篇文章主要为大家详细介绍了如何结合Lambda表达式和Optional,让Java更优雅地处理null值,感兴趣的小伙伴可以跟随小编一起学习一下... 目录场景 1:不为 null 则执行场景 2:不为 null 则返回,为 null 则返回特定值或抛出异常场景

SpringMVC获取请求参数的方法

《SpringMVC获取请求参数的方法》:本文主要介绍SpringMVC获取请求参数的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下... 目录1、通过ServletAPI获取2、通过控制器方法的形参获取请求参数3、@RequestParam4、@

SpringBoot应用中出现的Full GC问题的场景与解决

《SpringBoot应用中出现的FullGC问题的场景与解决》这篇文章主要为大家详细介绍了SpringBoot应用中出现的FullGC问题的场景与解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录Full GC的原理与触发条件原理触发条件对Spring Boot应用的影响示例代码优化建议结论F

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

SpringBoot条件注解核心作用与使用场景详解

《SpringBoot条件注解核心作用与使用场景详解》SpringBoot的条件注解为开发者提供了强大的动态配置能力,理解其原理和适用场景是构建灵活、可扩展应用的关键,本文将系统梳理所有常用的条件注... 目录引言一、条件注解的核心机制二、SpringBoot内置条件注解详解1、@ConditionalOn

通过Spring层面进行事务回滚的实现

《通过Spring层面进行事务回滚的实现》本文主要介绍了通过Spring层面进行事务回滚的实现,包括声明式事务和编程式事务,具有一定的参考价值,感兴趣的可以了解一下... 目录声明式事务回滚:1. 基础注解配置2. 指定回滚异常类型3. ​不回滚特殊场景编程式事务回滚:1. ​使用 TransactionT

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳