当前位置: 首页 > 面试题库 >

如何从Java调用GraphViz

严昀
2023-03-14
问题内容

如何从Java调用GraphViz,以及如何使用Java调用GraphViz函数?为了访问用于构建点图的GraphViz库,必须包含哪些必需的jar文件?是否有用于生成点图的示例程序


问题答案:

检查此
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 programs

/*$Id$*/
/*
 ******************************************************************************
 *                                                                            *
 *                    (c) Copyright 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.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 = "/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) {}
        }
    };

    /**
     * The dir. where temporary files will be created.
     */
  private static String TEMP_DIR = "/Users/seteropere/NetBeansProjects/TestApplication";

    /**
     * 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 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;
    }

    /**
     * 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;
    }

} // 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.dotDotGraph.pdf表示一个立方图。请记住:您只需要更改代码中两个参数的值:cfgPropTEMP_DIR

希望能有所帮助。



 类似资料:
  • 问题内容: 我有一个想从Java使用的Perl模块。是否可以使用Windows上的ActiveState Perl或Linux随附的通用Perl来调用此代码?我找到了对JPL的引用,但似乎不再维护了。 问题答案: Inline-Java是从Perl调用Java的常用库,因此本文提出了 org.perl.java 模块,该模块应允许按要求从Java调用Perl。 但是,由于不同的JVM的JNI实现的

  • 问题内容: 我需要从我的C ++程序中运行以下行: java -jar test.jar text1 text2 Java应用程序将给出一个float值并将其提供给c ++程序。 我怎样才能做到这一点?我从未从ms visual studio C ++文件中调用过Java东西。 问题答案: 当我直接在命令提示符下运行java命令时,它可以工作。但是当我从c ++文件运行命令时,错误显示“系统无法执

  • 问题内容: 我不是在寻找像Web服务这样的常见答案。我正在寻找在同一台机器上运行的轻量级解决方案。 编辑:我正在寻找Java中调用.NET方法的方法 问题答案: 我相信Java可以与COM对话,.NET可以公开COM接口。因此,这可能是一种非常轻巧的解决方案,不需要任何第三方。还可以选择使用套接字在程序之间进行通信,这不需要在计算机上安装大量的IIS实例。

  • 问题内容: 我需要从PowerShell调用Java程序(jar文件)。以下代码有效: 但是我需要在一个过程中运行该应用程序(使用)。 我正在尝试以下成功: 错误: 知道如何解决吗? 问题答案: 您将需要为Powershell使用以下格式: 或者您可以使用的其他选项是Start-job:

  • 问题内容: 我需要从Java调用C#函数,为此,我创建了以下代码。我有一个创建的Java头文件Authenticator.h,代码如下: 然后,我创建了一个身份验证的C#函数 然后,我尝试使用以下代码从C ++(项目创建dll)中调用C#函数; 最后创建一个需要从Java调用的dll。该dll已创建,并且可以在Java中很好地加载它,但是在Java中却收到此错误日志。我可能会错过什么。 问题答案:

  • 问题内容: 我有一个通常从命令行启动的Java程序。从命令行启动后,Java程序将一直运行直到被按下Ctrl + C退出或杀死另一个脚本中的命令为止。Java程序向控制台输出错误消息(如果有)。 现在,我想开发基于Express的NodeJs Web应用程序。当用户单击链接(运行)时,单击处理程序将调用Ajax请求,这将导致后端NodeJs脚本运行该Java程序(如果尚未运行)。另一个链接(停止)