檔案類型識別的方法有很多,如使用URLConnection對象的getContentType方法獲得:
File file = new File(“檔案路徑”);String type = file.toURL().openConnection().getContentType();
其他方法可參考資料:http://www.rgagnon.com/javadetails/java-0487.html中介紹的方法針對不同形式的資料進行解析。
若資料是位元組數組時,可參考程式:
/** * 根據圖片的bits位元組數組中的資料,識別圖片檔案類型,再根據prefix內容構造一個適當的檔案名稱 * @param bits 圖片位元組數組 * @param prefix 用於構造檔案名稱的首碼串 * @return 0元素存放檔案名稱,1元素存放檔案類型 */ public static String [] imgBitsDeal(byte[]bits, String prefix){ String [] rt = new String[2];// snippet for JMimeMagic lib// http://sourceforge.net/projects/jmimemagic/Magic parser = new Magic() ;MagicMatch match = null;try {match = parser.getMagicMatch(bits);rt[1] = match.getMimeType();//檔案類型rt[0] = prefix + "." + match.getExtension();//構造檔案名稱(含副檔名)//System.out.println(match.getMimeType()) ;//System.out.println(match.getExtension()) ;} catch (Exception e) {// TODO Auto-generated catch blockrt[0] = prefix + "." + "png";//預設檔案名稱rt[1] = "image/png";//預設檔案類型e.printStackTrace();} return rt; }
下載包地址: http://download.csdn.net/source/3551651