Wednesday, May 19, 2010

Looking for a file in a Folder

The java.io.FileFilter interface can be used to filter an array of files obtained when looking inside a directory.

An example implementation of FileFilter

class JarFileFilter implements FileFilter
{
public boolean accept(File file)
{
if(file.getName().toLowerCase().endsWith("jar"))
{
return true;
}
return false;
}
}

The above implementation class narrows down the list of files to only jar files.

This filter can be used when looking into a directory using java.io.File.

example snippet:

String myDirectoryLoc = "c:\myjars";
File myFolder = new File(myDirectoryLoc);

if(myFolder.isDirectory())
{
File[] myjars = myFolder.listFiles(new JarFileFilter);

if(myjars != null)
{
for (File f : myjars )
{
System.out.println("file: " + f.getName());
}
}
}

On successful execution you will get only the jar files in the specified folder.

Hope this is useful.

Cheers
Vinay

Monday, August 31, 2009

Loading Properties from a file in class path

A simple and smart way of loading a properties file which is located some where in the classpath

-------------------------

InputStream in = null;

Properties m_Properties = null;

in = ClassLoader.getSystemClassLoader().getResourceAsStream(fileName);

if (in != null)
{
m_Properties = new Properties ();

try {

m_Properties.load (in);

}

catch (IOException e)
{
e.printStackTrace();
}
}

Wednesday, July 8, 2009

Eliminating unnecessary log4j setup output

When using log4j for logging in your application, you may see a lot of log messages added by log4j when startup of the application which are not required. These will add to noise in your log files.

They will look something like

log4j: Retreiving an instance of org.apache.log4j.Logger.
log4j: Setting [Myclass] additivity to [false].
log4j: Level value for Myclass is [DEBUG].
log4j: Desired Level sub-class: [org.apache.log4j.Level]
log4j: Myclass level set to DEBUG
log4j: Class name: [org.apache.log4j.ConsoleAppender]
log4j: Setting property [target] to [System.out].
log4j: Parsing layout of class: "org.apache.log4j.PatternLayout"
log4j: Setting property [conversionPattern] to [%-5p %m%n].

These are the debug information from the logger itself. If you are using the XML config it looks like this:

log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true"
Turn the debug to false.