用Java实现获取文件类型的方法。

获取文件类型,可以理解为获取文件的扩展名。但是因为会存在某文件不具有扩展名,或者伪造扩展名等情况。不知道如何处理。请大侠赐教 ,感激不尽!!!

主要以下几种方法:

这个MimetypesFileMap类会映射出一个file的Mime Type,这些Mime Type类型是在activation.jar包里面的资源文件中定义的 

import javax.activation.MimetypesFileTypeMap;  
import java.io.File;  
  
class GetMimeType {  
  public static void main(String args[]) {  
    File f = new File("test.gif");  
    System.out.println("Mime Type of " + f.getName() + " is " +  
                         new MimetypesFileTypeMap().getContentType(f));  
    // expected output :  
    // "Mime Type of test.gif is image/gif"  
  }  
}

使用 java.net.URL 
警告:这个方法非常慢 
与上面所说的匹配后缀名类似。后缀名和mime-type的映射关系被定义在[jre_home]\lib\content-types.properties这个文件中 

import java.net.*;  
  
public class FileUtils{  
  public static String getMimeType(String fileUrl)  
    throws java.io.IOException, MalformedURLException  
  {  
    String type = null;  
    URL u = new URL(fileUrl);  
    URLConnection uc = null;  
    uc = u.openConnection();  
    type = uc.getContentType();  
    return type;  
  }  
  
  public static void main(String args[]) throws Exception {  
    System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT"));  
    // output :  text/plain  
  }  
}

还有一种方式:就是取文件名最后一个“.”后的内容,通过人来判断如

String fileName = "aaa.txt";

String fileType =“txt”//通过方法取出方法类型为

String type = "";

if( fileTyep.equals("txt")){

    type  = "记事本";

}else if(fileTyep.equals("img")){

    type  = "img图片";

}。。。。。

温馨提示:内容为网友见解,仅供参考
第1个回答  2013-04-19
肯定是要用后缀名来判断的,你用正则表达式去判断文件名就可以了。很简单
第2个回答  2013-04-20
is = new BufferedInputStream(new FileInputStream(fileName));
String mimeType = URLConnection.guessContentTypeFromStream(is);
if(mimeType == null) {
throw new IOException("can't get mime type of image");
}

追问

看起来这样确实可以取到文件扩展名,不过这种情况是不是表示需要读取文件,来获得文件头的信息,所以会不会影响性能呢。目前的业务是大量文件实时传过来,去判断类型。

本回答被提问者和网友采纳
第3个回答  2013-04-19
我这里有个工具类,就是太大了。没法贴出来。呵呵
相似回答