Java – Get real file extension

How to get real file extension in java?

One of the option by getting MIME type as :

mimeType= URLConnection.guessContentTypeFromName(file.getName());

Below has the advantage of going beyond mere use of file extension, and takes a peek at content

InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
 //...close stream

Using Java 7

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Test {
  public static void main(String[] args) throws IOException {
    Path filePath= Paths.get("c:/index.tif");
    System.out.println(Files.probeContentType(filePath));
  }
}

output : image/tiff



Using javax.activation.MimetypesFileTypeMap
import javax.activation.MimetypesFileTypeMap;
import java.io.File;

class GetMimeType {
  public static void main(String args[]) {
    File file = new File("index.gif");
    System.out.println("Mime Type of " + file.getName() + " is " +
                         new MimetypesFileTypeMap().getContentType(file));
  }
}

output:"Mime Type of index.gif is image/gif"


Using java.net.URL
import java.net.FileNameMap;
import java.net.URLConnection;

public class FileUtils {

  public static String getMimeType(String fileUrl)
      throws java.io.IOException
    {
      FileNameMap fileNameMap = URLConnection.getFileNameMap();
      String type = fileNameMap.getContentTypeFor(fileUrl);
      return type;
    }

    public static void main(String args[]) throws Exception {
      System.out.println(FileUtils.getMimeType("file://c:/index.txt"));
    }
  }


output : text/plain


Using Apache Tika
import java.io.File;
import java.io.FileInputStream;

import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;

public class Main {

    public static void main(String args[]) throws Exception {

    FileInputStream is = null;
    try {
      File f = new File("C:/index.docx");
      is = new FileInputStream(f);

      ContentHandler contenthandler = new BodyContentHandler();
      Metadata metadata = new Metadata();
      metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName());
      Parser parser = new AutoDetectParser();
      parser.parse(is, contenthandler, metadata);
      System.out.println("Mime: " + metadata.get(Metadata.CONTENT_TYPE));
      System.out.println("Title: " + metadata.get(Metadata.TITLE));
      System.out.println("Author: " + metadata.get(Metadata.AUTHOR));
      System.out.println("content: " + contenthandler.toString());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    finally {
        if (is != null) is.close();
    }
  }
}




Posted

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *