Monday, February 25, 2008

Get the File Type Icon with Java

This tutorial will shows how to get the file system icon for a specific file.

Getting the Small Icon
For all platforms, the FileSystemView class provides a method for getting the small icon (16x16). To get the icon, you must specify a file on the file system for which you want to get an icon. The following code example shows how to use this class to get the icon:

//Create a temporary file with the specified extension
File file = File.createTempFile("icon", ".doc");

FileSystemView view = FileSystemView.getFileSystemView();
Icon icon = view.getSystemIcon(file);

//Delete the temporary file
file.delete();

In the example above, a temporary file is created with the extension for the specified document type. This file is passed to the instance of the FileSystemView class to get the icon. This will return the default icon size which is 16x16 pixels on most platforms. Once you have the Icon, you can display it in most Swing controls such as a JLabel, JButton, JMenuItem, etc.

Getting the Large Icon
Unfortunately, there isn't a standard API call to get the larger icons (32x32) for document types. For platforms using the Sun JVM, there is an undocumented class called sun.awt.shell.ShellFolder that does provide this functionality. The following code is a modified version of our previous example with changes to show how to use the sun.awt.shell.ShellFolder class.
import sun.awt.shell.ShellFolder;
...
//Create a temporary file with the specified extension
File file = File.createTempFile("icon", ".doc");

ShellFolder shellFolder = ShellFolder.getShellFolder(file);
Icon icon = new ImageIcon(shellFolder.getIcon(true));

//Delete the temporary file
file.delete();

3 comments:

James said...

Thanks, this is exactly what I was looking for.

Rodrigo said...

This comment saved my life today. Thanks

Mr M said...

Very useful, thanks!