Showing posts with label Apache. Show all posts
Showing posts with label Apache. Show all posts

Sunday, 12 August 2012

How to Silently Close Resources in Java?

The following piece of code describes how to silently and properly close a stream resource in Java:
File f = new File("SomeFile.txt");
FileOutputStream fos = null;

try {

    fos = new FileOutputStream(f);<

    // Do something...

} catch (FileNotFoundException ex) {

    // Display error message

} finally {

    // Closing resource
    if ( fos != null )  {

        try {

            fos.close();

        } catch (IOException ex) {

            // Silently ignore it

        }

    }

}
Yet, the amount of code required to close each stream in finally is nothing but clutter which does not help with readability too. Fortunately, the Apache Commons library offers a tool solving this issue:
} finally {

    IOUtils.closeQuietly(out);

}

Friday, 10 August 2012

How to Convert a Byte Array Into an Hexadecimal String?

Trying to convert a byte array into an hexadecimal and back to the same byte array manually, can be tricky. The Hex class of the Apache Commons library offers a solution:
byte[] ba = { 4, 55, -27, 99, 42, 0, -1 };

String toHex = Hex.encodeHexString(ba);
byte[] retr = Hex.decodeHex(toHex.toCharArray());

System.out.println("Hexadecimal : " + toHex);
System.out.println("Expected    : " + Arrays.toString(ba));
System.out.println("Retrieved   : " + Arrays.toString(retr));

ba = new byte[0];
toHex = Hex.encodeHexString(ba);
retr = Hex.decodeHex(toHex.toCharArray());

System.out.println("Hexadecimal : " + toHex);
System.out.println("Expected    : " + Arrays.toString(ba));
System.out.println("Retrieved   : " + Arrays.toString(retr));
The generated output is:
Hexadecimal : 0437e5632a00ff
Expected    : [4, 55, -27, 99, 42, 0, -1]
Retrieved   : [4, 55, -27, 99, 42, 0, -1]

Hexadecimal :
Expected    : []
Retrieved   : []
More Java tips & tricks here.