Nov 24

The URL class can be used to parse a URL and retrieve the components such as host name

String urlstring = "http://www.objects.com.au/services/sherpa.html"
URL url = new URL(urlstring};
String host = url.getHost();   // returns "www.objects.com.au"

written by objects \\ tags: , ,

Nov 18

The following code can be used to convert a byte array (containing the bytes of a long) into a long.

	public static long byteArrayToLong(byte[] bytes) {
		long l = 0;
		for (int i=0; i<8; i++) {
			l <<= 8;
			l ^= (long) bytes[i] & 0xff;
		}
		return l;
	}

This is the reverse of “How to convert a long to a byte array“.

written by objects \\ tags: , , , ,

Nov 15

The BigDecimal constructors do not take the Locale into account when parsing number strings.
This means the following code will throw a NumberFormatException

Locale.setDefault(new Locale("nl", "NL"));
String s =  "2.343.298,09324798";
BigDecimal bd = new BigDecimal(s);

To parse localized strings as BigDecimal we instead need to use the DecimalFormat class

		Locale.setDefault(new Locale("nl", "NL"));
		String s =  "2.343.298,09324798";
		DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
		df.setParseBigDecimal(true);
		BigDecimal bd = (BigDecimal) df.parse(s);

written by objects \\ tags: , , , ,