Monday, April 06, 2009

Loading a non java file from jar

Scenario: You have a configuration or text or any other non java file of that kind. You have to package your application(apis) as jar(executable or non executable) for the client to use. However if the non java files used by your application are static(cannot change at runtime or by the user), you might want to package them as part of your archive. Here is the code to do exactly that:

public static InputStream loadFileFromJar(String fName){
return Constants.class.getClassLoader().getResourceAsStream(fName);
}

We all know that getResourceAsStream() method of ClassLoader will load any file from available classpath. However in case of jar(some times) the classloader could be different. So we play a small trick: We first load a class(could be even a dummy blank class) from the jar and acquire the handle to that classloader. Now we can be assured that this classloader will have access to all the resources inside the jar.

One more thing: You should keep your file either in base of the jar or in a relative folder.

Labels: , , ,

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: , , , , ,