1. 程式人生 > >使用Java獲取檔案型別

使用Java獲取檔案型別

Using Java 7
Files.html#probeContentType
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 source = Paths.get("c:/temp/0multipage.tif");
    System.out.println(Files.probeContentType(source));
    // output : image/tiff
  }
}
The default implementation is OS-specific and not very complete. It's possible to register a better detector, like for example Apache Tika, see Transparently improve Java 7 mime-type recognition with Apache Tika.
Using javax.activation.MimetypesFileTypeMap
activation.jar is required, it can be downloaded from 
http://java.sun.com/products/javabeans/glasgow/jaf.html.

The MimetypesFileMap class is used to map a File to a Mime Type. Mime types supported are defined in a ressource file inside the activation.jar.

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"
  }
}
The built-in mime-type list is very limited but a mechanism is available to add very easily more Mime Types/extensions.

The MimetypesFileTypeMap looks in various places in the user's system for MIME types file entries. When requests are made to search for MIME types in the MimetypesFileTypeMap, it searches MIME types files in the following order:

  1. Programmatically added entries to the MimetypesFileTypeMap instance.
  2. The file .mime.types in the user's home directory.
  3. The file <java.home>/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).
This method is interesting when you need to deal with incoming files with the filenames normalized. The result is very fast because only the extension is used to guess the nature of a given file.
Using java.net.URL
Warning : this method is very slow!.

Like the above method a match is done with the extension. The mapping between the extension and the mime-type is defined in the file [jre_home]\lib\content-types.properties

import java.net.*;

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
  }
}
A note from R. Lovelock :
I was trying to find the best way of getting the mime type of a file
and found your sight very useful. However I have now found a way of
getting the mime type using URLConnection that isn't as slow as the
way you describe.
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:/temp/test.TXT"));
      // output :  text/plain
    }
  }
Using Apache Tika
Tika is subproject of Lucene, a search engine. It is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries.

This package is very up-to-date regarding the filetypes supported, Office 2007 formats are supported (docs/pptx/xlsx/etc...).

Tika has a lot of dependencies ... almost 20 jars ! But it can do a lot more than detecting filetype. For example, you can parse a PDF or DOC to extract the text and the metadata very easily.

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:/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();
    }
  }
}
You can download here a ZIP containing the required jars if you want to check it out.
Using JMimeMagic
Checking the file extension is not a very strong way to determine the file type. A more robust solution is possible with the JMimeMagic library. JMimeMagic is a Java library (LGLP licence) that retrieves file and stream mime types by checking magic headers.
// snippet for JMimeMagic lib
//     http://sourceforge.net/projects/jmimemagic/

Magic parser = new Magic() ;
// getMagicMatch accepts Files or byte[],
// which is nice if you want to test streams
MagicMatch match = parser.getMagicMatch(new File("gumby.gif"));
System.out.println(match.getMimeType()) ;
Thanks to Jean-Marc Autexier and sygsix for the tip!
Using mime-util
Another tool is mime-util. This tool can detect using the file extension or the magic header technique.
import eu.medsea.mimeutil.MimeUtil;

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
    }
}
The nice thing about mime-util is that it is very lightweight. Only 1 dependency with slf4j
Using Droid
DROID (Digital Record Object Identification) is a software tool to perform automated batch identification of file formats.

DROID uses internal and external signatures to identify and report the specific file format versions of digital files. These signatures are stored in an XML signature file, generated from information recorded in the PRONOM technical registry. New and updated signatures are regularly added to PRONOM, and DROID can be configured to automatically download updated signature files from the PRONOM website via web services.

It can be invoked from two interfaces, a Java Swing GUI or a command line interface.

Aperture framework
Aperture is an open source library and framework for crawling and indexing information sources such as file systems, websites and mail boxes.

The Aperture code consists of a number of related but independently usable parts:

  • Crawling of information sources: file systems, websites, mail boxes
  • MIME type identification
  • Full-text and metadata extraction of various file formats
  • Opening of crawled resources
For each of these parts, a set of APIs has been developed and a number of implementations is provided.

相關推薦

Java獲取檔案型別/副檔名

import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; public class FileTypeUt

使用Java獲取檔案型別

Using Java 7 Files.html#probeContentType import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import jav

Java獲取檔案大小

一、通過length方法: 1、建立一個檔案: 1 File file = new File("E:\\全部軟體\\軟體壓縮包\\Windows7_W64_SP1_ent.iso"); 2、獲取檔案大小: /** * 獲取檔案長度 * @param

獲取檔案型別和檔名

#include<stdio.h>   #include<stdlib.h>   #include<string.h>   void get_extension(const char *file_name,char *ex

java 獲取檔案的字尾

public static void main(String[] args) { // TODO Auto-generated method stub String filename="D:\\新建.文字.文件.txt"; String newoldName =

java獲取檔案MD5,獲取字串MD5

 獲取md5值4個步驟: 1.建立MessageDigest物件md5。 2.使用md的update(byte[] buffer)方法將資料更新到md5物件中。 3.使用md5的digest()方法獲得摘要,該摘要是一個長度為16的陣列。 4.將該摘要陣列轉換為32位

java獲取檔案Mime Type的幾種方式

本文是在看了http://blog.csdn.net/chaijunkun/article/details/7046343之後實踐了一下,為自己加深印象再寫一遍。 jar包是用火狐下載的,放在哪裡忘了。是在寫檔案下載時,提示框要告訴使用者下載的是什麼型別的檔案用到的。 首先

獲取檔案型別使用 finfo_file 內建函式

今天檢視PHP文件發現原有的 mime_content_type 已廢棄,可以使用 finfo_file 內建函式 $finfo = finfo_open(FILEINFO_MIME_TYPE); // 返回 mime 型別 foreach (glob("*") as $

關於java獲取檔案路徑的幾種方式

第一種:  File f = new File(this.getClass().getResource("/").getPath());  System.out.println(f);  結果:  C:\Documents%20and%20Settings\Administ

獲取檔案型別

$finfo = finfo_open(FILEINFO_MIME_TYPE);//建立一個fileinfo資源 $mimetype = finfo_file($finfo,$file_dir); echo $mimetype;//video/mp4 finfo

java獲取檔案路徑的二種方式

方式一:使用類載入器 @Test public void test_path1() { String path = ClassLoader.getSystemResource("").getPath(); System.out.println(path);

Java獲取檔案路徑的幾種方法

第一種: File f = new File(this.getClass().getResource("/").getPath()); System.out.println(f); 結果: C:\Documents%20and%20Settings\Administrato

JAVA獲取檔案的MD5值

1.推薦如下方法: /** * 推薦此方法獲取檔案MD5 * @param path 檔案路徑 * @return */ public static String get

java獲取檔案路徑[轉]

平時寫程式的時候,很多時候提示檔案找不到,而丟擲了異常,現在整理如下 一 相對路徑的獲得 說明:相對路徑(即不寫明時候到底相對誰)均可通過以下方式獲得(不論是一般的java專案還是web專案) String relativelyPath=System.getProperty("user.dir"); 上述相對

java 獲取檔案返回 pdf檔案並列印

<%@ page language="java" import="java.util.*,java.io.*" pageEncoding="UTF-8"%> <% String pa

JAVA獲取檔案MD5值

/** * Md5校驗工具類 * @author Fengwx */ public class MD5Util { private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5',

java獲取檔案md5碼

最近下載了一些檔案,不是官方的,為了核對MD5碼寫了一個java版本的,小工具。 package pri.yang.MD5; import java.io.File; import java.io.FileInputStream; import java.io.FileN

Java獲取檔案字尾的方式

Using Java 7 import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public cl

java獲取檔案建立時間

方案一: private static Date getCreateTime(String fullFileName){ String str = null; try { Process p = Runtim

linux環境,java獲取檔案出現 (沒有那個檔案或目錄)

針對linux下,沒有那個檔案或目錄的原因:1、有可能是檔案沒有許可權,用 ls -l 命令查下許可權,如下:-rw-r-----. 1 root總共有10位,第一個'-'先不看,從第二個往後看。r 表示可讀取,w 表示可寫入,x 表示可執行。2、路徑有問題本屌的問題是因為