graphstream / gs-core

Graphstream core
http://graphstream-project.org/
Other
400 stars 108 forks source link

File reading example doesn't work #366

Open matwell-dev opened 2 years ago

matwell-dev commented 2 years ago

The example here: https://graphstream-project.org/doc/Tutorials/Reading-files-using-FileSource/ doesn't work. The construction of the file-source can throws an IOException.

Also, not a bug, but the example might as well display the constructed graph (I've defaulted it to Swing as a lowest-common denominator, as per some of the other examples), so I've added the code for that and tightened up the clean-up code in the case of an exception and the FileSource not being constructed.

At the risk of over-engineering an example, I might also have added only initialising the UI choice if not already defined, and also taking a list of (at least one) file-name parameters and processing them from the command-line, but it's your code! :o)

import org.graphstream.graph.Graph; import org.graphstream.graph.implementations.DefaultGraph; import org.graphstream.stream.file.FileSource; import org.graphstream.stream.file.FileSourceFactory;

import java.io.IOException;

public class TutorialFileSource {

public static void main(String ... args) {
    String filePath = "<<<YOUR-FILENAME-HERE>>>";

    System.setProperty("org.graphstream.ui", "swing");

    Graph g = new DefaultGraph("g");
    FileSource fs = null;

    try {
        fs = FileSourceFactory.sourceFor(filePath);

        fs.addSink(g);

        fs.begin(filePath);

        while (fs.nextEvents()) {
            // Optionally some code here ...
        }

        g.display();

    } catch( IOException e) {
        e.printStackTrace();
    }

    try {
        if (fs != null) fs.end();
    } catch( IOException e) {
        e.printStackTrace();
    } finally {
        if (fs != null) fs.removeSink(g);
    }
}

}