15 GB free disk space in the cloud RecentChanges 2014-04-24 XML TXT

Java Snippets

Generate a unique number

    import java.math.BigInteger;
    import java.rmi.server.UID;
    public class UniqueNumber {
        public static void main(String[] args) {
            UID uid = new UID();
            String s = uid.toString();
            s = s.replaceAll(":", "");
            s = s.replaceAll("-", "");
            s = s.toUpperCase();
            BigInteger bi = new BigInteger(s, 16);
            System.out.println("bi = " + bi);

See what classes are configured to log

It's easy to make a typo in the so if you want to make sure that you're actually logging the right stuff, you can put the following snippet in your main for a visual check:

    LogManager lm = LogManager.getLogManager();
    for(Enumeration e = lm.getLoggerNames(); e.hasMoreElements();) {
        System.out.println((String) e.nextElement());

You'll probably use the classname as the unique identifier with which you create the Logger instance. Be sure NOT to type the classname manually or with a constant, just do it as follows:

    public class Scratchpad {
        Logger logger = Logger.getLogger(this.getClass().getName());
        // Class code goes here

Format a date

To format a date in Java, use the following code snippet. The result should be date = 17-Sep-2004:

    Date date = new Date();
    // If you use more than three Ms, the month will print out full
    SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
    System.out.println("date = " + format.format(date));

To parse a date:

    String theDate = "19790919";
    DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
    Date date = (Date)formatter.parse(theDate);

FTP a file

You are using the Jakarta Commons Net library to transfer files for the user. When it fails, you want to display a correct error message. Now, if you would just read the Javadoc to check the exceptions that the connect() method of the FTPClient class throws, you wouldn't get any wiser: it says it throws SocketException and IOException. However, look carefully at the first exception; it's a superclass of a couple of finer-grained exceptions. The code snippet below gives you all the options:

    FTPClient client;
    try {
        client = new FTPClient();
        client.connect("");  // an IP address is also fine
    } catch (UnknownHostException uhe) {
        System.out.println("The host name was not valid");
    } catch (NoRouteToHostException nrthe) {
        System.out.println("The IP address was not valid");
    } catch (ConnectException ce) {
        String msg = ce.getMessage();
        if(msg.indexOf("timed out") != -1) {
            System.out.println("timeout occurred, host is down or disconnected");
        } else {
            System.out.println("Error occurred while passing commands to the" +
    } finally {
        if (client != null && client.isConnected()) {

Format a long with leading zeros

Say you want to print a long, but you must make sure it contains at least five digits. If not, the number needs to be prefixed with zeros.

    long l = 355;
    String s;
    if (l < 10000) {
      // this has less than five digits
      DecimalFormat df = new DecimalFormat("00000");
      s = df.format(l);
    } else {
      s = l + "";

To do quick-'n'-dirty timing

    boolean debug = true;
    long startTime = System.currentTimeMillis();
    if (debug) {
        out.println("Elapsed: " + ( System.currentTimeMillis() - startTime ) +
                    " milliseconds");


To get the full stacktrace in a String (this should've been part of the API):

    try {
        // Do stuff
    } catch (Exception e) {
        StringBuffer sb = new StringBuffer();
        StackTraceElement st[] = e.getStackTrace();
        sb.append(e.getMessage() + "\n");
        for (int i = 0; i < st.length; i++)
            sb.append("at " + st[i].getClassName() + "." +
                      st[i].getMethodName() + "(" +
                      st[i].getFileName()+": " + 
                      st[i].getLineNumber() + ")");

Long-running queries

To put a long-running query in the background, and keep refreshing your JSP until it's done, see page Long-running queries There are better ways, though.

Split number from postfix in postal code

This example uses a regular expression to parse a house number.

	String regex = "^[0-9]+";
	String s = "123a";
	Pattern p = Pattern.compile(regex);
	Matcher m = p.matcher(s);
	if(m.find()) {
	} else {
		System.out.println("Not found!");