Get the File Type Icon with Java

This Java tutorial 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();


14 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!

zavs said...

cool, thanks!

AUMY said...

Excellent i was looking for it

Anonymous said...

THANKSSSSS!!!!!!!!!! JUST WHAT IVE BEEN LOOKING FOR !!!!!!!!

Anonymous said...

Using this code gives the same icon for all file types. Its a plain white icon. What do i need to do get the correct file icon for each different file type?

thanks

Rensu Theart said...

Thanks! Just what I needed. And such a simple example. :-)

suja said...

hi,

will i be able to use this icon as an image in web applications. I am not using swing but i need this file type icons for displaying it in a web apps.

Please help me out

Anonymous said...

Man this is so useful.... Many thanks...

Anonymous said...

Thank you very much, very useful

Anonymous said...

Really great!!! thankyou a lot!!!

i love you men!!!

prashant said...

I am getting the basic file icon for all types of files.
can you please help to get file type specific icons.

Anonymous said...

Thanks... exactly what i was looking for

Post a Comment