Java File content type


 

Java File content type

In this section, you will learn how to get the content type of the specified file.

In this section, you will learn how to get the content type of the specified file.

Java File content type

In this section, you will learn how to get the content type of the specified file.

Description of code:

This is essential part of the file. In various applications, there is a use of content type. Here we have used java.net.* package to find out the content type of the file.

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.

Here is the code:

import java.net.*;

class FileContentType {
  public static String getType(String fileUrlthrows Exception {
    URL u = new URL(fileUrl);
    URLConnection uc = u.openConnection();
    String type = uc.getContentType();
    return type;
  }

  public static void main(String[] argsthrows Exception {
    String file = "C:/rose.jpg";
    String type = getType("file:" + file);
    System.out.println("Content type of file " + file + " is: " + type);
  }
}

In the above code, we have used URL and URLConnection class to find the content type or mime type of the specified file.

Output:

Content type of file "C:/rose.jpg is: image/jpeg

Ads