Friday, March 20, 2009

Java code to delete entire folder structure with files in it

Ever tried file.delete() and wondered why your non empty directory is not deleted? Irony with java's api is that it returns a boolean when we expect it to either delete or fail! Here is a simple recursive function that will do the trick of deleting any file or folder with or without nested structure.

If you use this method in your application, do so at your own risk. I have not tested it for boundary conditions...
public static void deleteResource(File file){
if (file != null)
if (file.isFile())
file.delete();
else if (file.isDirectory()){
File[] resources = file.listFiles();
if (resources.length == 0)
file.delete();
else {
for (File resource: resources)
deleteResource(resource);
deleteResource(file);
}
}
}

Labels: , , , , ,

Running multiple tomcat as service on same machine?

Often while hosting tomcat server test instances, due to lack of hardware you are required to host multiple instances of your tomcat server software on same physical box. Moreover tomcat is so lightweight, it makes all the sense in the world to host multiple tomcats on the same machine. Unfortunately Tomcat installation wizard does not provide you the option to configure your "listening port" number. (Default is 8080). This is how I configured my tomcat instances:

  • Download the zip of your favourite tomcat version from tomcat.apache.org. Do not download the exe, use a zip. This is the key!
  • Unzip the software and copy it into multiple folders indicating multiple server instance. Use some naming convention for ease of identification. I append the http port number to directory name.
  • You will have to change at least 3 port numbers: 8080, 8005, 8009. (for tomcat 5.5 and 6)
  • While deciding on new port numbers, follow a naming convention. For example, if I had four instances running on the same machine, my port numbers would be: 5580/5505/5509, 6680/6605/6609 and 7780/7705/7709.
  • Now do search in multiple files and "replace all " to replace all port number references. Editplus does a good job!
  • Registering your servers as service: Navigate to the bin folder of your tomcat installation. Run the command service.bat install . It is again a good idea to append your port number in the service name. Perform this exercise with all your instances.
  • Open your services console. You can start/stop tomcat here.

Labels: , , , , , , ,