FileDocCategorySizeDatePackage
FSDirectory.javaAPI DocApache Lucene 1.4.314533Wed May 19 17:46:34 BST 2004org.apache.lucene.store

FSDirectory

public final class FSDirectory extends Directory
Straightforward implementation of {@link Directory} as a directory of files.

If the system property 'disableLuceneLocks' has the String value of "true", lock creation will be disabled.

see
Directory
author
Doug Cutting

Fields Summary
private static final Hashtable
DIRECTORIES
This cache of directories ensures that there is a unique Directory instance per path, so that synchronization on the Directory can be used to synchronize access between readers and writers. This should be a WeakHashMap, so that entries can be GC'd, but that would require Java 1.2. Instead we use refcounts...
private static final boolean
DISABLE_LOCKS
public static final String
LOCK_DIR
Directory specified by org.apache.lucene.lockdir or java.io.tmpdir system property
private static MessageDigest
DIGESTER
private byte[]
buffer
A buffer optionally used in renameTo method
private File
directory
private int
refCount
private File
lockDir
private static final char[]
HEX_DIGITS
So we can do some byte-to-hexchar conversion below
Constructors Summary
private FSDirectory(File path, boolean create)


         
    directory = path;

    if (LOCK_DIR == null) {
      lockDir = directory;
    }
    else {
      lockDir = new File(LOCK_DIR);
    }
    if (create) {
      create();
    }

    if (!directory.isDirectory())
      throw new IOException(path + " not a directory");
  
Methods Summary
public final synchronized voidclose()
Closes the store to future operations.

    if (--refCount <= 0) {
      synchronized (DIRECTORIES) {
        DIRECTORIES.remove(directory);
      }
    }
  
private synchronized voidcreate()

    if (!directory.exists())
      if (!directory.mkdirs())
        throw new IOException("Cannot create directory: " + directory);

    String[] files = directory.list();            // clear old files
    for (int i = 0; i < files.length; i++) {
      File file = new File(directory, files[i]);
      if (!file.delete())
        throw new IOException("Cannot delete " + files[i]);
    }

    String lockPrefix = getLockPrefix().toString(); // clear old locks
    files = lockDir.list();
    for (int i = 0; i < files.length; i++) {
      if (!files[i].startsWith(lockPrefix))
        continue;
      File lockFile = new File(lockDir, files[i]);
      if (!lockFile.delete())
        throw new IOException("Cannot delete " + files[i]);
    }
  
public final OutputStreamcreateFile(java.lang.String name)
Creates a new, empty file in the directory with the given name. Returns a stream writing this file.

    return new FSOutputStream(new File(directory, name));
  
public final voiddeleteFile(java.lang.String name)
Removes an existing file in the directory.

    File file = new File(directory, name);
    if (!file.delete())
      throw new IOException("Cannot delete " + name);
  
public final booleanfileExists(java.lang.String name)
Returns true iff a file with the given name exists.

    File file = new File(directory, name);
    return file.exists();
  
public final longfileLength(java.lang.String name)
Returns the length in bytes of a file in the directory.

    File file = new File(directory, name);
    return file.length();
  
public final longfileModified(java.lang.String name)
Returns the time the named file was last modified.

    File file = new File(directory, name);
    return file.lastModified();
  
public static final longfileModified(java.io.File directory, java.lang.String name)
Returns the time the named file was last modified.

    File file = new File(directory, name);
    return file.lastModified();
  
public static org.apache.lucene.store.FSDirectorygetDirectory(java.lang.String path, boolean create)
Returns the directory instance for the named location.

Directories are cached, so that, for a given canonical path, the same FSDirectory instance will always be returned. This permits synchronization on directories.

param
path the path to the directory.
param
create if true, create, or erase any existing contents.
return
the FSDirectory for the named file.


                                                            
        
        
    return getDirectory(new File(path), create);
  
public static org.apache.lucene.store.FSDirectorygetDirectory(java.io.File file, boolean create)
Returns the directory instance for the named location.

Directories are cached, so that, for a given canonical path, the same FSDirectory instance will always be returned. This permits synchronization on directories.

param
file the path to the directory.
param
create if true, create, or erase any existing contents.
return
the FSDirectory for the named file.

    file = new File(file.getCanonicalPath());
    FSDirectory dir;
    synchronized (DIRECTORIES) {
      dir = (FSDirectory)DIRECTORIES.get(file);
      if (dir == null) {
        dir = new FSDirectory(file, create);
        DIRECTORIES.put(file, dir);
      } else if (create) {
        dir.create();
      }
    }
    synchronized (dir) {
      dir.refCount++;
    }
    return dir;
  
public java.io.FilegetFile()

    return directory;
  
private java.lang.StringBuffergetLockPrefix()

    String dirName;                               // name to be hashed
    try {
      dirName = directory.getCanonicalPath();
    } catch (IOException e) {
      throw new RuntimeException(e.toString());
    }

    byte digest[];
    synchronized (DIGESTER) {
      digest = DIGESTER.digest(dirName.getBytes());
    }
    StringBuffer buf = new StringBuffer();
    buf.append("lucene-");
    for (int i = 0; i < digest.length; i++) {
      int b = digest[i];
      buf.append(HEX_DIGITS[(b >> 4) & 0xf]);
      buf.append(HEX_DIGITS[b & 0xf]);
    }

    return buf;
  
public final java.lang.String[]list()
Returns an array of strings, one for each file in the directory.

    return directory.list();
  
public final org.apache.lucene.store.LockmakeLock(java.lang.String name)
Constructs a {@link Lock} with the specified name. Locks are implemented with {@link File#createNewFile() }.

In JDK 1.1 or if system property disableLuceneLocks is the string "true", locks are disabled. Assigning this property any other string will not prevent creation of lock files. This is useful for using Lucene on read-only medium, such as CD-ROM.

param
name the name of the lock file
return
an instance of Lock holding the lock


                                                                               
       
    StringBuffer buf = getLockPrefix();
    buf.append("-");
    buf.append(name);

    // create a lock file
    final File lockFile = new File(lockDir, buf.toString());

    return new Lock() {
      public boolean obtain() throws IOException {
        if (DISABLE_LOCKS)
          return true;

        if (!lockDir.exists()) {
          if (!lockDir.mkdirs()) {
            throw new IOException("Cannot create lock directory: " + lockDir);
          }
        }

        return lockFile.createNewFile();
      }
      public void release() {
        if (DISABLE_LOCKS)
          return;
        lockFile.delete();
      }
      public boolean isLocked() {
        if (DISABLE_LOCKS)
          return false;
        return lockFile.exists();
      }

      public String toString() {
        return "Lock@" + lockFile;
      }
    };
  
public final InputStreamopenFile(java.lang.String name)
Returns a stream reading an existing file.

    return new FSInputStream(new File(directory, name));
  
public final synchronized voidrenameFile(java.lang.String from, java.lang.String to)
Renames an existing file in the directory.

    File old = new File(directory, from);
    File nu = new File(directory, to);

    /* This is not atomic.  If the program crashes between the call to
       delete() and the call to renameTo() then we're screwed, but I've
       been unable to figure out how else to do this... */

    if (nu.exists())
      if (!nu.delete())
        throw new IOException("Cannot delete " + to);

    // Rename the old file to the new one. Unfortunately, the renameTo()
    // method does not work reliably under some JVMs.  Therefore, if the
    // rename fails, we manually rename by copying the old file to the new one
    if (!old.renameTo(nu)) {
      java.io.InputStream in = null;
      java.io.OutputStream out = null;
      try {
        in = new FileInputStream(old);
        out = new FileOutputStream(nu);
        // see if the buffer needs to be initialized. Initialization is
        // only done on-demand since many VM's will never run into the renameTo
        // bug and hence shouldn't waste 1K of mem for no reason.
        if (buffer == null) {
          buffer = new byte[1024];
        }
        int len;
        while ((len = in.read(buffer)) >= 0) {
          out.write(buffer, 0, len);
        }

        // delete the old file.
        old.delete();
      }
      catch (IOException ioe) {
        throw new IOException("Cannot rename " + from + " to " + to);
      }
      finally {
        if (in != null) {
          try {
            in.close();
          } catch (IOException e) {
            throw new RuntimeException("Cannot close input stream: " + e.getMessage());
          }
        }
        if (out != null) {
          try {
            out.close();
          } catch (IOException e) {
            throw new RuntimeException("Cannot close output stream: " + e.getMessage());
          }
        }
      }
    }
  
public java.lang.StringtoString()
For debug output.

    return "FSDirectory@" + directory;
  
public voidtouchFile(java.lang.String name)
Set the modified time of an existing file to now.

    File file = new File(directory, name);
    file.setLastModified(System.currentTimeMillis());