N5 Tutorial

Post description
Author

John Bogovic

Published

February 9, 2024

Modified

February 9, 2024

This is an basic tutorial of the N5 API for Java developers.

Readers and writers

N5Readers and N5Writers form the basis of the N5 API and allow you to read and write data, respectively. We generally recommend making using N5Factory to create readers and writers:

// N5Factory can make N5Readers and N5Writers
var factory = new N5Factory();

// trying to open a container does not yet exist will throw an error 
// var n5Reader = factory.openReader("my-container.n5");

// creating a writer creates a container at the given location
// if it does not already exist
var n5Writer = factory.openWriter("my-container.n5");

// now we can make a reader
var n5Reader = factory.openReader("my-container.n5");

// test if the container exists
n5Reader.exists(""); // true
true
Source: N5-Tutorial.ipynb
// "" and "/" both refer to the root of the container
n5Reader.exists("/"); // true
true

The N5 API gives you access to a number of different storage formats: HDF5, Zarr, and N5’s own format. N5Factory’s convenience methods try to infer the storage format from the path you give it:

factory.openWriter("my-container.h5").getClass();    // class org.janelia.saalfeldlab.n5.hdf5.N5HDF5Writer
factory.openWriter("my-container.n5").getClass();    // class org.janelia.saalfeldlab.n5.N5FSWriter
factory.openWriter("my-container.zarr").getClass();  // class org.janelia.saalfeldlab.n5.zarr.N5ZarrWriter
class org.janelia.saalfeldlab.n5.zarr.N5ZarrWriter

In fact, it is possible to read with N5Writers since every N5Writer is also an N5Reader, so from now on, we’ll just be using the n5Writer.

Groups

N5 containers form hierarchies of groups - think “nested folders on your file system.” It’s easy to create groups and test if they exist:

n5Writer.createGroup("foo");
n5Writer.createGroup("foo/bar");
n5Writer.createGroup("lorum/ipsum/dolor/sit/amet");

n5Writer.exists("lorum/ipsum");      // true
n5Writer.exists("not/a/real/group"); // false

The list method lists groups that are children of the given group:

Arrays.toString(n5Writer.list(""));     // [lorum, foo]
Arrays.toString(n5Writer.list("foo"));  // [bar]

and deepList recursively lists every descendent of the given group:

Arrays.toString(n5Writer.deepList(""));

Arrays