Search poi

How To Use the POIFS APIs

How To Use the POIFS APIs

This document describes how to use the POIFS APIs to read, write, and modify files that employ a POIFS-compatible data structure to organize their content.

Revision History

  • 02.10.2002 - completely rewritten from original documents on sourceforge

Target Audience

This document is intended for Java developers who need to use the POIFS APIs to read, write, or modify files that employ a POIFS-compatible data structure to organize their content. It is not necessary for developers to understand the POIFS data structures, and an explanation of those data structures is beyond the scope of this document. It is expected that the members of the target audience will understand the rudiments of a hierarchical file system, and familiarity with the event pattern employed by Java APIs such as AWT would be helpful.

Glossary

This document attempts to be consistent in its terminology, which is defined here:

Term Definition
Directory A special file that may contain other directories and documents.
DirectoryEntry Representation of a directory within another directory.
Document A file containing data, such as word processing data or a spreadsheet workbook.
DocumentEntry Representation of a document within a directory.
Entry Representation of a file in a directory.
File A named entity, managed and contained by the file system.
File System The POIFS data structures, plus the contained directories and documents, which are maintained in a hierarchical directory structure.
Root Directory The directory at the base of a file system. All file systems have a root directory. The POIFS APIs will not allow the root directory to be removed or renamed, but it can be accessed for the purpose of reading its contents or adding files (directories and documents) to it.

Reading a File System

This section covers reading a file system. There are two ways to read a file system; these techniques are sketched out in the following table, and then explained in greater depth in the sections following the table.

Technique Advantages Disadvantages
Conventional Reading Simpler API similar to reading a conventional file system.
Can read documents in any order.
All files are resident in memory, whether your application needs them or not.
Event-Driven Reading Reduced footprint -- only the documents you care about are processed.
Improved performance -- no time is wasted reading the documents you're not interested in.
More complicated API.
Need to know in advance which documents you want to read.
No control over the order in which the documents are read.
No way to go back and get additional documents except to re-read the file system, which may not be possible, e.g., if the file system is being read from an input stream that lacks random access support.

Conventional Reading

In this technique for reading, the entire file system is loaded into memory, and the entire directory tree can be walked by an application, reading specific documents at the application's leisure.

Preparation

Before an application can read a file from the file system, the file system needs to be loaded into memory. This is done by using the org.apache.poi.poifs.filesystem.POIFSFileSystem class. Once the file system has been loaded into memory, the application may need the root directory. The following code fragment will accomplish this preparation stage:

// need an open InputStream; for a file-based system, this would be appropriate:
// InputStream stream = new FileInputStream(fileName);
POIFSFileSystem fs;
try
{
    fs = new POIFSFileSystem(inputStream);
}
catch (IOException e)
{
    // an I/O error occurred, or the InputStream did not provide a compatible
    // POIFS data structure
}
DirectoryEntry root = fs.getRoot();

Assuming no exception was thrown, the file system can then be read.

Note: loading the file system can take noticeable time, particularly for large file systems.

Reading the Directory Tree

Once the file system has been loaded into memory and the root directory has been obtained, the root directory can be read. The following code fragment shows how to read the entries in an org.apache.poi.poifs.filesystem.DirectoryEntry instance:

// dir is an instance of DirectoryEntry ...
for (Iterator iter = dir.getEntries(); iter.hasNext(); )
{
    Entry entry = (Entry)iter.next();
    System.out.println("found entry: " + entry.getName());
    if (entry instanceof DirectoryEntry)
    {
        // .. recurse into this directory
    }
    else if (entry instanceof DocumentEntry)
    {
        // entry is a document, which you can read
    }
    else
    {
        // currently, either an Entry is a DirectoryEntry or a DocumentEntry,
	// but in the future, there may be other entry subinterfaces. The
	// internal data structure certainly allows for a lot more entry types.
    }
}

Reading a Specific Document

There are a couple of ways to read a document, depending on whether the document resides in the root directory or in another directory. Either way, you will obtain an org.apache.poi.poifs.filesystem.DocumentInputStream instance.

DocumentInputStream

The DocumentInputStream class is a simple implementation of InputStream that makes a few guarantees worth noting:

  • available() always returns the number of bytes in the document from your current position in the document.
  • markSupported() returns true.
  • mark(int limit) ignores the limit parameter; basically the method marks the current position in the document.
  • reset() takes you back to the position when mark() was last called, or to the beginning of the document if mark() has not been called.
  • skip(long n) will take you to your current position + n (but not past the end of the document).

The behavior of available means you can read in a document in a single read call like this:

byte[] content = new byte[ stream.available() ];
stream.read(content);
stream.close();

The combination of mark, reset, and skip provide the basic mechanisms needed for random access of the document contents.

Reading a Document From the Root Directory

If the document resides in the root directory, you can obtain a DocumentInputStream like this:

// load file system
try
{
    DocumentInputStream stream = filesystem.createDocumentInputStream(documentName);
    // process data from stream
}
catch (IOException e)
{
    // no such document, or the Entry represented by documentName is not a
    // DocumentEntry
}
Reading a Document From an Arbitrary Directory

A more generic technique for reading a document is to obtain an org.apache.poi.poifs.filesystem.DirectoryEntry instance for the directory containing the desired document (recall that you can use getRoot() to obtain the root directory from its file system). From that DirectoryEntry, you can then obtain a DocumentInputStream like this:

DocumentEntry document = (DocumentEntry)directory.getEntry(documentName);
DocumentInputStream stream = new DocumentInputStream(document);

Event-Driven Reading

The event-driven API for reading documents is a little more complicated and requires that your application know, in advance, which files it wants to read. The benefit of using this API is that each document is in memory just long enough for your application to read it, and documents that you never read at all are not in memory at all. When you're finished reading the documents you wanted, the file system has no data structures associated with it at all and can be discarded.

Preparation

The preparation phase involves creating an instance of org.apache.poi.poifs.eventfilesystem.POIFSReader and to then register one or more org.apache.poi.poifs.eventfilesystem.POIFSReaderListener instances with the POIFSReader.

POIFSReader reader = new POIFSReader();
// register for everything
reader.registerListener(myOmnivorousListener);
// register for selective files
reader.registerListener(myPickyListener, "foo");
reader.registerListener(myPickyListener, "bar");
// register for selective files
reader.registerListener(myOtherPickyListener, new POIFSDocumentPath(),
     "fubar");
reader.registerListener(myOtherPickyListener, new POIFSDocumentPath(
    new String[] { "usr", "bin" ), "fubar");

POIFSReaderListener

org.apache.poi.poifs.eventfilesystem.POIFSReaderListener is an interface used to register for documents. When a matching document is read by the org.apache.poi.poifs.eventfilesystem.POIFSReader, the POIFSReaderListener instance receives an org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent instance, which contains an open DocumentInputStream and information about the document.

A POIFSReaderListener instance can register for individual documents, or it can register for all documents; once it has registered for all documents, subsequent (and previous!) registration requests for individual documents are ignored. There is no way to unregister a POIFSReaderListener.

Thus, it is possible to register a single POIFSReaderListener for multiple documents - one, some, or all documents. It is guaranteed that a single POIFSReaderListener will receive exactly one notification per registered document. There is no guarantee as to the order in which it will receive notification of its documents, as future implementations of POIFSReader are free to change the algorithm for walking the file system's directory structure.

It is also permitted to register more than one POIFSReaderListener for the same document. There is no guarantee of ordering for notification of POIFSReaderListener instances that have registered for the same document when POIFSReader processes that document.

It is guaranteed that all notifications occur in the same thread. A future enhancement may be made to provide multi-threaded notifications, but such an enhancement would very probably be made in a new reader class, a ThreadedPOIFSReader perhaps.

The following table describes the three ways to register a POIFSReaderListener for a document or set of documents:

Method Signature What it does
registerListener(POIFSReaderListener listener) registers listener for all documents.
registerListener(POIFSReaderListener listener, String name) registers listener for a document with the specified name in the root directory.
registerListener(POIFSReaderListener listener, POIFSDocumentPath path, String name) registers listener for a document with the specified name in the directory described by path

POIFSDocumentPath

The org.apache.poi.poifs.filesystem.POIFSDocumentPath class is used to describe a directory in a POIFS file system. Since there are no reserved characters in the name of a file in a POIFS file system, a more traditional string-based solution for describing a directory, with special characters delimiting the components of the directory name, is not feasible. The constructors for the class are used as follows:

Constructor example Directory described
new POIFSDocumentPath() The root directory.
new POIFSDocumentPath(null) The root directory.
new POIFSDocumentPath(new String[ 0 ]) The root directory.
new POIFSDocumentPath(new String[ ] { "foo", "bar"} ) in Unix terminology, "/foo/bar".
new POIFSDocumentPath(new POIFSDocumentPath(new String[] { "foo" }), new String[ ] { "fu", "bar"} ) in Unix terminology, "/foo/fu/bar".

Processing POIFSReaderEvent Events

Processing org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent events is relatively easy. After all of the POIFSReaderListener instances have been registered with POIFSReader, the POIFSReader.read(InputStream stream) method is called.

Assuming that there are no problems with the data, as the POIFSReader processes the documents in the specified InputStream's data, it calls registered POIFSReaderListener instances' processPOIFSReaderEvent method with a POIFSReaderEvent instance.

The POIFSReaderEvent instance contains information to identify the document (a POIFSDocumentPath object to identify the directory that the document is in, and the document name), and an