Java check mime type

Getting Mime type in Java

In this tutorial, I am showing how to get mime type of a file in java using Java 7 Files and URLConnection class.

You can select right one from the below listed, which suits your needs.

Using Java 7 Files .probeContentType

// using java 7 probeContentType  String mimeType = Files.probeContentType(path);  System.out.println(mimeType);

Using With URLConnection getContentType

// getContentType  URLConnection connection = file.toURL().openConnection();  System.out.println(connection.getContentType()); 

Using URLConnection guessContentTypeFromName

// guessContentTypeFromName  System.out.println(URLConnection.guessContentTypeFromName(file.getName()));

Using URLConnection getFileNameMap

// getFileNameMap  System.out.println(URLConnection.getFileNameMap().getContentTypeFor(file.getName())); 

You can find the complete example of finding mimes type of a file below with all the above described ways.

package com.javatips; import java.io.File; import java.io.IOException; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; public class MimeExample  public static void main(String[] args) throws IOException   File file = new File("java.png");  Path path = file.toPath(); // using java 7 probeContentType  String mimeType = Files.probeContentType(path);  System.out.println(mimeType); // getContentType  URLConnection connection = file.toURL().openConnection();  System.out.println(connection.getContentType()); // guessContentTypeFromName  System.out.println(URLConnection.guessContentTypeFromName(file.getName())); // getFileNameMap  System.out.println(URLConnection.getFileNameMap().getContentTypeFor(file.getName())); > >

Output

image/png image/png image/png image/png

Источник

Находки программиста

Решения конкретных задач программирования. Java, Android, JavaScript, Flex и прочее. Настройка софта под Linux, методики разработки и просто размышления.

вторник, 11 октября 2011 г.

Как получить mime-type файла в Java

Теоретически есть три способа получить информацию о типе файла. Все эти способы имеют свои преимущества и, конечно же, недостатки.

Способ первый: не заглядываем внутрь
Проще всего определить тип файла по его расширению. Знакомая с детства, понятная, быстрая и весьма неточная схема. Собственно, точность зависит от того, насколько полным и актуальным является используемый нами справочник расширений. Чтобы не хардкодить свой справочник используем, например javax.activation.MimetypesFileTypeMap:

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

class GetMimeType public static void main( String args[]) File f = new File ( «gumby.gif» );
System. out .println( «Mime Type of » + f.getName() + » is » +
new MimetypesFileTypeMap().getContentType(f));
// expected output :
// «Mime Type of gumby.gif is image/gif»
>
>

  1. Programmatically added entries to the MimetypesFileTypeMap instance.
  2. The file .mime.types in the user’s home directory.
  3. The file /lib/mime.types.
  4. The file or resources named META-INF/mime.types.
  5. The file or resource named META-INF/mimetypes.default (usually found only in the activation.jar file).

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
>
>

Тут мы практически открываем соединение с файлом по протоколу file:// и читаем заголовок content-type из полученного соединения.
Чуть более быстрый способ:

import java.net.FileNameMap;
import java.net.URLConnection;

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

public static void main( String args[]) throws Exception System. out .println(FileUtils.getMimeType( «file://c:/temp/test.TXT» ));
// output : text/plain
>
>

Способ третий: Посмотрим-таки внутрь!
Самый надёжный способ, определяющий тип файла по его содержимому. Точен настолько, насколько это возможно, достаточно быстр. Но требует использования большого числа сторонних библиотек. Например, используя 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 static void main( String args[]) throws Exception

FileInputStream is = null ;
try File f = new File ( «C:/Temp/mime/test.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();
// OOXMLParser parser = new OOXMLParser();
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();
>
>
>

Библиотека — часть поискового движка Lucene — подключает в рантайме около 20 (!) зависимостей (в общей сложности мегабайт на 18). Смотрите сами, нужно ли оно вам в проекте.

Более компактный вариант — использовать библиотеку JMimeMagic:

public static String getMime( String path) MagicMatch match = null ;
try match = Magic.getMagicMatch( new File (path), true );
> catch (Exception e) e.printStackTrace(System.err);
>
return match.getMimeType();
>

Плюсы: всего две зависимости: Apache Common logging и Jakarta Oro (уже не разрабатывается). Вместе с зависимостями размер библиотеки едва превышает 150 Kb.
Минусы: сравнительно невысокая точность — «не узнаёт» несколько популярных форматов файлов, иногда «убивает» наше приложение с ошибкой OutOfMemoryError. На исправление ошибок вряд ли стоит рассчитывать: последняя версия вышла в 2006 году.

public class Main public static void main( String [] args) MimeUtil.registerMimeDetector( «eu.medsea.mimeutil.detector.MagicMimeMimeDetector» );
File f = new File ( «c:/temp/mime/test.doc» );
Collection mimeTypes = MimeUtil.getMimeTypes(f);
System. out .println(mimeTypes);
// output : application/msword
>
>

Минусы: несколько больший размер, есть проблема с «узнаванием» текстовых файлов: все они (включая html) воспринимаются как «application/octet-stream». Плюсы: достаточно высокая точность определения типов, всего одна зависимость (SLF4J), более стабильная работа.

Как правило, более «навороченные» библиотеки, распознающие больше форматов соответственно и «тяжелее». Я уверен, что есть ещё достаточно много библиотек, не описанных в статье, вольный перевод которой я тут попытался представить вашему вниманию. Если у кого-нибудь возникнет желание познакомиться с какой-нибудь подробнее, дайте ссылку в комментариях, я с удовольствием посмотрю на неё и опишу результат знакомства.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Java library to detect files’ MIME types

License

overview/mime-types

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Ever see «application/octet-stream» or «text/plain» or «text/html»? Those are called MIME types. («MIME» stands for Multi-purpose Internet Mail Extensions.)

If your Java program has files and needs to figure out their MIME types, this library will help.

import org.overviewproject.mime_types.MimeTypeDetector // . File file = new File("foo.txt"); MimeTypeDetector detector = new MimeTypeDetector(); String mimeType = detector.detectMimeType(file); // "text/plain" // . or . InputStream stream = new ByteArrayInputStream("words".getBytes("utf-8")) String mimeType = detector.detectMimeType("filename", stream); // "text/plain"

No library can figure out MIME types perfectly. But there’s a standard, called shared-mime-info. This library follows its algorithm to the letter.

You need two things to detect a file’s type:

The bytes aren’t always needed; for speed, you can pass a callback instead of the actual bytes, and this library will only invoke the callback when it’s absolutely necessary. There’s an async version, too.

For a method that matches the files you have, read the MimeTypeDetector docs.

Big thanks to Medsea Business Solutions S.L. for most of this code. I merely adjusted the API. (The original project at http://sourceforge.net/p/mime-util/ seems to be dead.)

About

Java library to detect files’ MIME types

Источник

Читайте также:  Index and find python
Оцените статью