java可使用FileSystemView和ShellFolder類獲取文件的小圖標和大圖標,以下是詳細代碼:
import?java.awt.FlowLayout;import?java.io.File;
import?java.io.FileNotFoundException;
import?javax.swing.Icon;
import?javax.swing.ImageIcon;
import?javax.swing.JFrame;
import?javax.swing.JLabel;
import?javax.swing.filechooser.FileSystemView;
public?class?GetFileIcon?{
/**
*?@param?args */public?static?void?main(?String[]?args?)
{
StringfilePath=?"D:/sheet1.xlsx";
Filef=?new?File(?filePath?);
JFramefrm=?new?JFrame();
frm.setSize(?300,?200?);
frm.setLocationRelativeTo(?null?);
frm.setDefaultCloseOperation(?JFrame.EXIT_ON_CLOSE?);
frm.setVisible(?true?);
frm.setLayout(?new?FlowLayout(?10,?10,?FlowLayout.LEADING?)?);
JLabel?sl?=?new?JLabel(?"小圖標"?);
frm.add(?sl?);
JLabel?bl?=?new?JLabel(?"大圖標"?);
frm.add(?bl?);
sl.setIcon(?getSmallIcon(?f?)?);
bl.setIcon(?getBigIcon(?f?)?);
}
/**
*?獲取小圖標 *?@param?f *?@return */private?static?Icon?getSmallIcon(?File?f?)
{
if?(?f?!=?null?&&?f.exists()?)
{
FileSystemView?fsv?=?FileSystemView.getFileSystemView();
return(fsv.getSystemIcon(?f?)?);
}
return(null);
}
/**
*?獲取大圖標 *?@param?f *?@return */private?static?Icon?getBigIcon(?File?f?)
{
if?(?f?!=?null?&&?f.exists()?)
{
try?{
sun.awt.shell.ShellFolder?sf?=?sun.awt.shell.ShellFolder.getShellFolder(?f?);
return(new?ImageIcon(?sf.getIcon(?true?)?)?);
}?catch?(?FileNotFoundException?e?)?{
/*?TODO?Auto-generated?catch?block?*/
e.printStackTrace();
}
}
return(null);
}
}