Friday, December 28, 2012

Java - Get content type of a particular file



In many occasion you may require to check content type of a particular file. For example if a file is uploaded, it's not enough to check only file extension. For additional security you should also check the actual content type of a file so latter while processing the file no exception occurs. File could be Image, Excel, Text etc.

Let's see how this can be achieved in Java.

URL - This class represents a Uniform Resource Locator. It point to a particular resource, resource can be either a file , directory or an object. Here it refers to a file.

URLConnection - This is the super class of all classes that represent a communication link between an application and a URL.

openConnection() - This is the method of URL class which represents a connection to the remote object referred to by the URL.

getContentType() - This method of URLConnection class returns the content type of the file.


Please see the self explanatory Java code below.


If protocol is unknown to URL class it will throw below exception.

Exception in thread "main" java.net.MalformedURLException: unknown protocol: c
at java.net.URL.(URL.java:574)
at java.net.URL.(URL.java:464)
at java.net.URL.(URL.java:413)

1 comment:

  1. Οne οf the most сommon scenarіos is the
    ωoman whο is facіng divοrcе and finԁs it necessarу
    tо cοnsult ρгofesѕіоnals to helρ her deal wіth the еmotіonal сonsequences inherent to end of a marriаge.
    You can be treated mοrе quickly than on the ΝHS and
    will have much better chοіce over where and when уou're treated. If you don't κnow the ansωer to a quеstion, be honest about
    it.

    Alsо vіѕіt mу blog: Vietnetmedia.com

    ReplyDelete