Obtener el tipo MIME de un fichero

2195 vistas

Esta información podemos conseguirla gracias a la clase java.net.URLConnection.

Veamos un ejemplo:



java
  1. public static String getMIMEType(File file){
  2.   if(file.isDirectory()){return "directorio";}
  3.  
  4.   if(!file.exists()){return "fichero innexistente";}
  5.  
  6.   try{
  7.       URL url = file.toURL();
  8.       URLConnection connection = url.openConnection();
  9.       return connection.getContentType();
  10.   }catch(MalformedURLException mue){
  11.       return mue.getMessage();
  12.   }catch(IOException ioe){
  13.       return ioe.getMessage();
  14.       }
  15. }



Para más "seguridad" podemos usar el método estático guessContentTypeFromStream que, a diferencia de getContentType (o guessContentTypeFromName), intenta determinar el tipo MIME leyendo directamente los primeros bytes del InputStream.