From JavaProgramming
/* UseService?.java */ import javax.naming.*; import java.io.File; import java.util.Hashtable; /** * Demonstrates the use of a JNDI service (Java Naming and Directory Interface) * Before using this program you must download a File System Server from * Sun at http://java.sun.com/products/jndi/serviceproviders.html * The donwloaded zip file should contain two jar files: * fscontext.jar and providerutil.jar * These files can be placed in <jdk path, i.e. c:\jdk1.3>\jre\lib\ext * thereby making the jar files available to the JVM without * needing to adjust the classpath * **/ class UseService? { public static void main(String[] args) { // Set up the environment for creating the initial context Hashtable env = new Hashtable(); // Set up context for JNDI file system service env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); // This will allow you to inspect the folder c:\java env.put(Context.PROVIDER_URL, "file:/java"); // ctx must be initialised, when calling Context.close() in the finally block Context ctx = null; try { // Create the initial context // May generate NamingException? ctx = new InitialContext(env); // Call lookup() on this object, to lookup a file relative to the // /java folder. // Cast return type from lookup() into a File type // May generate NamingException? File file = (File)ctx.lookup("JNDI/UseService?.java"); // For example, you can specify "JNDI/UseService?.java" to // find out information about your current file (!). System.out.println("Length: " + file.length()); System.out.println("Can read: " + file.canRead()); // Output: // Length: xxxx // Can read: true } // Remember to catch any NamingExceptions? and // display any error information on the console. catch (NamingException? ex) { System.out.println(ex.getMessage()); } finally { try { // Allways close server connections in a finally block. // If close() is called in the try block it might not be called // when an exception occurs on a previous line. // Not closing the connection will leave dangling resources on the server // May generate NamingException? ctx.close(); } catch (NamingException? ex) { System.out.println(ex.getMessage()); } } } }