Dimitri Missoh
enthusiastic technologist and problem solver

January 25th, 2009

Interested in any key events of an SWT Application?

There is actually a way to achieve that. In an appropriate location of your code add:

Display.getDefault().addFilter(SWT.KeyDown, listener);

where the listener to implement can look like:

1
2
3
4
5
Listener listener = new Listener() {
   public void handleEvent(Event event) {
      // do some amazing things with the event
   }
};

Don’t forget to unregister your listener on dispose.

January 18th, 2009

How to get the MIME Type of a file in Java

Have you ever been confronted with the problem of getting the right MIME type for a given file? Using the file extension is not necessarily the best way, since the file can simply not have any extension such as on a Unix system (on Unix systems, file extensions are optional). On this kind of systems, other methods are used to identify the format of a file. One of them is the use of magic numbers. A magic number is a 2 bytes identifier at the beginning of the document.

There are some Java libraries that combine the use of file extension and magic number (also known as magic header) to determine the MIME type of a file. My favorite one is mime-util. The main benefit of this library is, that it consists of a single jar file without any dependencies to third party libraries.

To use this library in your code:

  • Download the jar file from http://sourceforge.net/projects/mime-util,
  • add the jar file to your project dependencies (i.e. add it to the CLASSPATH) and
  • call the static helper method MimeUtil.getMimeType(File) as shown in the snippet below:
1
2
3
4
5
6
7
8
9
10
11
12
13
import eu.medsea.util.MimeUtil;
 
public class Tester {
   public String getMimeType(String fileName){
      File file = new File(fileName);
      String unknownMimeType = "application/x-unknown-mime-type";
      String mimetype = MimeUtil.getMimeType(file);
      if (mimetype == null) {
	mimetype = unknownMimeType;
      }
      return mimetype;
   }
}

Additional information:

For an extensive list of MIME types with their corresponding RFC please check out the following sites:

The online article http://www.rgagnon.com/javadetails/java-0487.html adresses this issue in detail.