com.ccg.io
Class Utility

java.lang.Object
  extended by com.ccg.io.Utility

public class Utility
extends Object

Collection of handy little utilities related to java.io. Seems like there are many common static type methods which are always being retyped in order to provide some general functionality.

Since:
1.0
Version:
$Revision: 1.1.1.1 $
Author:
$Author: pkb $
See Also:
java.io

Constructor Summary
Utility()
           
 
Method Summary
static URL convertRelativeURL(URL base, String path)
          Conversion of string to URL allowing relative path.
static File getHomeFile(String path)
          Create a File object relative to the user's home directory.
static InputStream getInputStream(String name)
          Flexible method to convert a String into a InputStream This method takes a String as a named resource.
static byte[] getLineSeparatorBytes()
          Get the line separator used by the current JVM environment when writing text files as a array of bytes.
static String getLineSeparatorString()
          Get the line separator used by the current JVM environment when writing text files as a string.
static Lookup getLookup(String name)
          Load a set of Lookup properties.
static ObjectInputStream getObjectInputStream(String name)
          Flexible method to convert a String into a ObjectInputStream This method used the getInputStream(java.lang.String) method and attempts to convert its results to directly to a ObjectInputStream.
static Properties getProperties(String name)
          Load a set of properties.
static Reader getReader(String name)
          Flexible method to convert a String into a Reader This method takes a String as a named resource.
static URL trimURL(URL url, int how_many)
          A "up directory" for URL's.
static String urlJoin(String[] s)
          Do a "smart" join of multiple strings to form a URL.
static String urlJoin(String b, String s)
          Do a "smart" join of two strings to form a URL.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Utility

public Utility()
Method Detail

convertRelativeURL

public static URL convertRelativeURL(URL base,
                                     String path)
Conversion of string to URL allowing relative path.

The URL class provides the URL.URL(URL,String) constructor to construct a URL using a base URL and a string which can override fields. However, if you use this constructor in a fashion like:

 URL url = new URL(new URL("http://mole/fred"),"src/test.html"));
 

You'll discover that the resulting URL will be: "http:/mole/src/test.html". This method provides an alternative solution and will produce a URL in the form of "http:/mole/fred/src/test.html" in this condition.

This method allows one to define a "anchor" point (base URL) for source files and then refer to the source files via a relative path. It can be very handy when working with the document and code base URL's provided by applets.

The following sample program demonstrates how different base URL and path strings are combined:



import java.net.URL;
import com.ccg.io.Utility;

public class U {
  public static void main(String[] args) {
    try {
      URL[] bases = {
        new URL("http://mole/~pkb"),
        new URL("http://mole/"),
        new URL("http://mole/java/")
      };

      for (int i = 0; i < args.length; i++) {
        for (int j = 0; j < bases.length; j++) {
          URL result = Utility.convertRelativeURL(bases[j],args[i]);
          System.out.println("new URL(\""+bases[j]+
                             "\",\""+args[i]+
                             "\")=\""+result+"\"");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

If you save the above programe to a file named "U.java", you should be able to compile and then invoke it via:

 javac U.java
 java U http://my.yahoo http://yahoo.com/ //yahoo.com \
 this/doc.txt /this/doc.txt
 

You should see output like the following:

   
new URL("http://mole/~pkb","http://my.yahoo")="http://my.yahoo/"
new URL("http://mole/","http://my.yahoo")="http://my.yahoo/"
new URL("http://mole/java/","http://my.yahoo")="http://my.yahoo/"
new URL("http://mole/~pkb","http://yahoo.com/")="http://yahoo.com/"
new URL("http://mole/","http://yahoo.com/")="http://yahoo.com/"
new URL("http://mole/java/","http://yahoo.com/")="http://yahoo.com/"
new URL("http://mole/~pkb","//yahoo.com")="http://yahoo.com/"
new URL("http://mole/","//yahoo.com")="http://yahoo.com/"
new URL("http://mole/java/","//yahoo.com")="http://yahoo.com/"
new URL("http://mole/~pkb","this/doc.txt")="http://mole/~pkb/this/doc.txt"
new URL("http://mole/","this/doc.txt")="http://mole/this/doc.txt"
new URL("http://mole/java/","this/doc.txt")="http://mole/java/this/doc.txt"
new URL("http://mole/~pkb","/this/doc.txt")="http://mole/this/doc.txt"
new URL("http://mole/","/this/doc.txt")="http://mole/this/doc.txt"
new URL("http://mole/java/","/this/doc.txt")="http://mole/this/doc.txt"

Parameters:
base - Your "anchor" point to use if the "path" specified is relative or omits protocol type information from the URL. If you pass null, then an attempt will be made to convert "path" directly to a URL - if this fails you will get null back.
path - The string you want to convert to a URL. If you pass null, then you will be "base" returned.
Returns:
A URL which is the result of combining "base" with "path" - or null if unable to do so.
Since:
1.0
See Also:
getInputStream(java.lang.String)

urlJoin

public static String urlJoin(String b,
                             String s)
Do a "smart" join of two strings to form a URL.

It is common to form URLs by "joining" together one or more strings. For example, consider the following:

 String rootUrl = "http://joe.com/";
 String subDir = "local/";
 String fileName = "joe.html";
 String url = rootUrl+subDir+fileName;
 

 

The above would work, and result in the string "http://joe.com/local/joe.html".

However, the above form requires the user to worry about slashes ("/"), at the start or end. If the "rootUrl" had been defined as "http://joe.com", it would have come out as "http://joe.comlocal/joe.html" which is probably not what you want.

This method takes the "worry" out of this situation, it sticks a slash ("/") between strings (or removes an extra one). So, using this makes life much easier. As an example ALL of the following will expand to the same URL ("http://joe.comlocal/joe.html").

 urlJoin("http://joe.com/local","joe.html");
 urlJoin(urlJoin("http://joe.com","local"),"joe.html");
 urlJoin(urlJoin("http://joe.com/","/local/"),"/joe.html");
 urlJoin(urlJoin("http://joe.com","/local"),"joe.html")
 

Parameters:
b - The base of the URL string (you can pass null - its treated like a empty string).
s - The sub directory to join on to the base (you can pass null - its treated like a empty string).
Returns:
The resulting URL after the strings are joined.
Since:
1.0
See Also:
urlJoin(String[])

urlJoin

public static String urlJoin(String[] s)
Do a "smart" join of multiple strings to form a URL.

It is common to form URLs by "joining" together one or more strings. For example, consider the following:

 String rootUrl = "http://joe.com/";
 String subDir = "local/";
 String fileName = "joe.html";
 String url = rootUrl+subDir+fileName;
 

 

The above would work, and result in the string "http://joe.com/local/joe.html".

However, the above form requires the user to worry about slashes ("/"), at the start or end. If the "rootUrl" had been defined as "http://joe.com", it would have come out as "http://joe.comlocal/joe.html" which is probably not what you want.

This method takes the "worry" out of this situation, it sticks a slash ("/") between strings (or removes an extra one). So, using this makes life much easier. As an example ALL of the following will expand to the same URL ("http://joe.comlocal/joe.html").

 String[] s0 = { "http://joe.com/local","joe.html" };
 String u0 = urlJoin(s0);

 String[] s1 = { "http://joe.com","local","joe.html" };
 String u1 = urlJoin(s1);

 String[] s2 = { "http://joe.com/","/local/","/joe.html" };
 String u2 = urlJoin(s2);

 String[] s3 = { "http://joe.com","/local","joe.html" };
 String u3 = urlJoin(s3);
 

Parameters:
sa - Array of strings to "smartly" join together into a single URL (must not be null - though it is ok for entries in the array to be null - we'll skip over them).
Returns:
The resulting URL after the strings are joined.
Since:
1.0
See Also:
urlJoin(String,String)

trimURL

public static URL trimURL(URL url,
                          int how_many)
A "up directory" for URL's. This method takes a URL and allows one to trim off one or more file/directories at the end of the URL. The most common use of this method is to trim off the ending file name of a URL to leave one pointing at the URL directory where the file was located. Here are some examples:
 trimURL("http://my.yahoo.com",1) -> "http://my.yahoo.com"
 trimURL("http://my.yahoo.com/",1) -> "http://my.yahoo.com"
 trimURL("http://mole/pkb",1) -> "http://mole"
 trimURL("http://mole/pkb/",1) -> "http://mole/pkb"
 trimURL("http://mole/pkb/t.html",1) -> "http://mole/pkb"
 trimURL("http://mole/pkb/u/z/t.html",3) -> "http://mole/pkb"
 

This can be particularily handy when dealing with the document base of applets.

Parameters:
url - The URL you want to "trim" (it may be null in which case you'll get null back).
how_far_up - How many '/' characters do you want to trim from the URL (think of this almost as how many directories to move up). If you specify more than are present, then you'll be returned just the root host/port URL.
Returns:
The "trimmed" resulting URL.
Since:
1.0
See Also:
convertRelativeURL(java.net.URL, java.lang.String)

getInputStream

public static InputStream getInputStream(String name)
                                  throws FileNotFoundException
Flexible method to convert a String into a InputStream This method takes a String as a named resource. It then tries real hard to find a InputStream which can be associated. It searches in the most efficient method as possible. It tries in the following order:

Parameters:
name - The name of the resource/file/URL which we want to access as a InputStream
Returns:
A InputStream if able to do so.
Throws:
FileNotFoundException - If this method is unable to convert the specified String to a input stream.
Since:
1.0
See Also:
getObjectInputStream(java.lang.String)

getReader

public static Reader getReader(String name)
                        throws FileNotFoundException
Flexible method to convert a String into a Reader This method takes a String as a named resource. It then tries real hard to find a Reader which can be associated. It searches in the most efficient method as possible. It tries in the following order:

Parameters:
name - The name of the resource/file/URL which we want to access as a Reader
Returns:
A Reader if able to do so.
Throws:
FileNotFoundException - If this method is unable to convert the specified String to a Reader.
Since:
1.0
See Also:
getInputStream(java.lang.String)

getObjectInputStream

public static ObjectInputStream getObjectInputStream(String name)
                                              throws FileNotFoundException,
                                                     StreamCorruptedException,
                                                     IOException
Flexible method to convert a String into a ObjectInputStream This method used the getInputStream(java.lang.String) method and attempts to convert its results to directly to a ObjectInputStream. This is a very flexible way to open up a input stream of objects.

Parameters:
name - The name of the resource/file/URL which we want to access as a InputStream
Returns:
A ObjectInputStream if found - read to start reading objects from.
Throws:
FileNotFoundException - If this method is unable to convert the specified String to a input stream.
StreamCorruptedException - If the InputStream opened is not a valid ObjectInputStream.
IOException - Other IO exception(s) associated with ObjectInputStreams
Since:
1.0
See Also:
getInputStream(java.lang.String)

getProperties

public static Properties getProperties(String name)
                                throws FileNotFoundException,
                                       IOException
Load a set of properties. This method attempts to load a standard Java property file from the named resource and return it as a Properties object. It tries very hard to find the property file by using the getInputStream(java.lang.String) defined above.

Parameters:
name - The name of the resource/file/URL which we want to access as a InputStream
Returns:
A Properties with the properties loaded from the specified source.
Throws:
FileNotFoundException - If this method is unable to convert the specified String to a input stream.
IOException - If there is a problem reading the propeties from the specified source.
Since:
1.0
See Also:
getLookup(java.lang.String)

getLookup

public static Lookup getLookup(String name)
                        throws FileNotFoundException,
                               IOException
Load a set of Lookup properties. This method attempts to load a standard Java property file from the named resource and return it as a generic Lookup object. It tries very hard to find the property file by using the getInputStream(java.lang.String) defined above.

Parameters:
name - The name of the resource/file/URL which we want to access as a InputStream
Returns:
A Lookup with the properties loaded.
Throws:
FileNotFoundException - If this method is unable to convert the specified String to a input stream.
IOException - If there is a problem reading the propeties from the specified source.
Since:
1.0
See Also:
Lookup, getProperties(java.lang.String)

getHomeFile

public static File getHomeFile(String path)
                        throws SecurityException
Create a File object relative to the user's home directory. Kept finding myself wanting to create configuration files and/or data files for the user which were relative to the user's home directory. This routine allows one to do this simply. Typically you would invoke it in a manner like:
 File f = Utility.getHomeBasedFile("etc/.my.config");
 

On a Windows based system, the returned File object might be something like "u:\etc\.my.config". On a Unix based system, it might come back as "/home/pkb/etc/.my.config". The two nice features being:

  1. The "/" (or "\") characters will automatically be translated for you depending on the host system.
  2. The user's home directory will be prepended to the front of the file name.

This method is currently only intended to be used for relative based paths. If you pass an absolute path its behaviour is undefined.

Parameters:
path - A path string (preferably relative like "etc/.my.config"), which you would like to open. Must not be null or zero length.
Returns:
A File object which is composed of the user's home directory and the "path" specified. All slash (both forward and backward will be converted to the native systems form).
Throws:
SecurityException - If there is a problem determining the user's home directory.
Since:
1.0

getLineSeparatorString

public static String getLineSeparatorString()
Get the line separator used by the current JVM environment when writing text files as a string.

The first time this method is invoked, we will attempt to determine this from the JVM's "line.separator" system property. If we are unable to determine from the system (which should not happen), we will go with the Unix default of "\n".

All subsequent invocations will return what was determined on the first invocation (and will hence be quick).

Returns:
String corresponding the the end of line separator used by the current JVM's file system for text files (typically "\n", "\r", or "\r\n").
Since:
1.0
See Also:
getLineSeparatorBytes()

getLineSeparatorBytes

public static byte[] getLineSeparatorBytes()
Get the line separator used by the current JVM environment when writing text files as a array of bytes.

This method simply returns the byte array representation of the value return by the getLineSeparatorString() method.

The array returned is allocated each time, so if you modify it, you won't affect other code which makes use of this method.

Returns:
Array of bytes corresponding the the end of line separator used by the current JVM's file system for text files (typically "\n", "\r", or "\r\n").
Since:
1.0
See Also:
getLineSeparatorString()


Copyright 1998-1998-2006 null. All Rights Reserved.