10
Sep '11

Store the system properties in an XML file

import java.io.*;

/**
* @param fileName the file to save the properties in
*/
public void storeSystemProperties(String fileName) {
	try {
		Properties prop = System.getProperties();

		FileOutputStream fileOut = new FileOutputStream(new File(fileName));

		prop.storeToXML(fileOut, "Properties");
		fileOut.flush();
		fileOut.close();
	}
	catch(FileNotFoundException e) {
		System.out.println(e.getMessage());
	}
	catch(IOException e) {
		System.out.println(e.getMessage());
	}
}
27
Aug '11

Read a config file, parse it and add key/value pairs to a hashmap

import java.io.*;
import java.util.HashMap;

/**
* @param configFile the location of the configuration file
* @return the produced HashMap
*/
public HashMap importConfig(String configFile) {
	HashMap config = new HashMap;

	try {
		BufferedReader bufRead = new BufferedReader(new FileReader(configFile));

		while(bufRead.ready()) {
			String line = bufRead.readLine();

			if(!line.startsWith("#") && line.indexOf("=") != -1) {
				//Trim out whitespace, explode at equals and put key/value pairs into the config HashMap
				int splitPos = line.indexOf("=");
				String key = line.substring(0, splitPos).trim();
				String value = line.substring(splitPos+1, line.length()).trim();

				if(!key.equals("") && !value.equals("")) {
					config.put(key, value);
				}
			}
		}

		bufRead.close();
	}
	catch (FileNotFoundException e) {
		System.out.println(e.getMessage());
	}
	catch (IOException e) {
		System.out.println(e.getMessage());
	}

	return config;
}
01
Jul '11

Pass it a filename and it’ll pass you back the Hash. Simple as that!

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public String getMD5Hash(String fileName) {
	String hash = "";

	try {
		File file = new File(fileName);
		FileReader fileRead = new FileReader(file);
		MessageDigest md = MessageDigest.getInstance("MD5");

		char[] chars = new char[1024];
		int charsRead = 0;

		do {
			charsRead = fileRead.read(chars, 0, chars.length);

			if(charsRead >= 0) {
				md.update(new String(chars, 0, charsRead).getBytes());
			}
		}
		while(charsRead >= 0);

		hash = new BigInteger(1, md.digest()).toString(16);
	}
	catch (NoSuchAlgorithmException e){}
	catch (IOException e){}

	return hash;
}