Java Tips

Using MessageFormat to control the formatting of variables

MessageFormat allows a developer to control the formatting of variables in output text. It is a powerful class, as the following example shows.

String message =
 "A while ago ({1,date}, around about {1,time,short}), there " +
 "was a humble developer named Geppetto who slaved for " +
 "{0,number,integer} days with {2,number,percent} complete user " +
 "requirements.";

Object[ ] variables =
 new Object[ ] { new Integer(4), new Date( ), new Double(0.21) }

String output = MessageFormat.format( message, variables );

Hidden in the message is a little language that describes the formatting of the output. An example value for ‘output’ is shown below:

A while ago (Nov 3, 2002, around about 1:35 AM), there was a humble
developer named Geppetto who slaved for 4 days with 21% complete user requirements.

If the same message needs to be pushed out again and again with different variables, then a MessageFormat object can be built and given the message. Here’s a modification of the above example:

//    String output = MessageFormat.format( message, variables );
//    becomes:

      MessageFormat formatter = new MessageFormat(message);
      String output = formatter.format(variables);

Using recursion to delete a directory structure

static public void deleteDirectory(File dir) throws IOException {

  if( (dir == null) || !dir.isDirectory) {
    throw new IllegalArgumentException(
      "Argument "+dir+" is not a directory." );
  }

  File[ ] entries = dir.listFiles( );
  int sz = entries.length;

  for(int i=0; i < sz; i++) {
    if(entries[i].isDirectory()) {
        deleteDirectory(entries[i]);
    } else {
        entries[i].delete();
    }
  }
  dir.delete();
}

Converting objects to byte arrays

static private byte[] object2Bytes(Object o) throws IOException
{
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(baos);
  oos.writeObject(o);
  return baos.toByteArray();
}

Converting byte arrays to objects

static private Object bytes2Object(byte raw[]) throws IOException, ClassNotFoundException
{
  ByteArrayInputStream bais = new ByteArrayInputStream(raw);
  ObjectInputStream ois = new ObjectInputStream(bais);
  Object o = ois.readObject();
  return o;
}