2015-06-17 4 views
0

Попробованного следующего:Detect типа файла на основе содержимого

import java.io.IOException; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.nio.file.spi.FileTypeDetector; 
import org.apache.tika.Tika; 
import org.apache.tika.mime.MimeTypes; 

/** 
* 
* @author kiriti.k 
*/ 
public class TikaFileTypeDetector { 

    private final Tika tika = new Tika(); 

    public TikaFileTypeDetector() { 
     super(); 
    } 

    public String probeContentType(Path path) throws IOException { 
     // Try to detect based on the file name only for efficiency 
     String fileNameDetect = tika.detect(path.toString()); 
     if (!fileNameDetect.equals(MimeTypes.OCTET_STREAM)) { 
      return fileNameDetect; 
     } 

     // Then check the file content if necessary 
     String fileContentDetect = tika.detect(path.toFile()); 
     if (!fileContentDetect.equals(MimeTypes.OCTET_STREAM)) { 
      return fileContentDetect; 
     } 

     // Specification says to return null if we could not 
     // conclusively determine the file type 
     return null; 
    } 

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

     Tika tika = new Tika(); 

     // expects file path as the program argument 
     if (args.length != 1) { 
      printUsage(); 
      return; 
     } 

     Path path = Paths.get(args[0]); 

     TikaFileTypeDetector detector = new TikaFileTypeDetector(); 
     // Analyse the file - first based on file name for efficiency. 
     // If cannot determine based on name and then analyse content 
     String contentType = detector.probeContentType(path); 

     System.out.println("File is of type - " + contentType); 
    } 

    public static void printUsage() { 
     System.out.print("Usage: java -classpath ... " 
       + TikaFileTypeDetector.class.getName() 
       + " "); 
    } 
} 

выше программа проверяет на основании только расширение файла. Как заставить его также проверить тип контента (mime), а затем определить тип. Я использую tika-app-1.8.jar в netbean 8.0.2. Что мне не хватает?

+0

Что вы подразумеваете под "check content type"? – immibis

+0

определить тип Mime на основе содержимого файла, но не по расширению – kittu

+0

Apache tika должен это делать, но не работает – kittu

ответ

2

код проверяет расширение файла и возвращает первый тип MIME, основанный на том, что, если он находит результат. Если вы хотите, чтобы он сначала проверял содержимое, просто переключите два оператора:

public String probeContentType(Path path) throws IOException { 

    // Check contents first 
    String fileContentDetect = tika.detect(path.toFile()); 
    if (!fileContentDetect.equals(MimeTypes.OCTET_STREAM)) { 
     return fileContentDetect; 
    } 

    // Try file name only if content search was not successful 
    String fileNameDetect = tika.detect(path.toString()); 
    if (!fileNameDetect.equals(MimeTypes.OCTET_STREAM)) { 
     return fileNameDetect; 
    } 

    // Specification says to return null if we could not 
    // conclusively determine the file type 
    return null; 
} 

Помните, что это может иметь огромное влияние на производительность.

+0

Большое вам спасибо. Вместо того, чтобы отслеживать программу для содержимого файла, вы начали изучать меня lol – kittu

0

Вы можете использовать Files.probeContentType(path)

+0

Пробовал это ... Его проверка основана на типе файла. Допустим, пользователь меняет расширение вручную и запускает программу для проверки типа. Then 'Files.probeContentType (path)' показывает модифицированный тип расширения – kittu