- Class FileTypeDetector
- Constructor Summary
- Method Summary
- Methods declared in class java.lang.Object
- Constructor Details
- FileTypeDetector
- Method Details
- probeContentType
- Java detect file types
- Constructor Summary
- Method Summary
- Methods declared in class java.lang.Object
- Constructor Detail
- FileTypeDetector
- Method Detail
- probeContentType
- Определение типов файлов в Java
- О примерах
- Files.probeContentType (Path) [JDK 7]
Class FileTypeDetector
A file type detector is a concrete implementation of this class, has a zero-argument constructor, and implements the abstract methods specified below.
The means by which a file type detector determines the file type is highly implementation specific. A simple implementation might examine the file extension (a convention used in some platforms) and map it to a file type. In other cases, the file type may be stored as a file attribute or the bytes in a file may be examined to guess its file type.
Constructor Summary
Method Summary
Methods declared in class java.lang.Object
Constructor Details
FileTypeDetector
Method Details
probeContentType
Probes the given file to guess its content type. The means by which this method determines the file type is highly implementation specific. It may simply examine the file name, it may use a file attribute, or it may examine bytes in the file. The probe result is the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type as defined by RFC 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. The string must be parsable according to the grammar in the RFC 2045.
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Java detect file types
A file type detector for probing a file to guess its file type. A file type detector is a concrete implementation of this class, has a zero-argument constructor, and implements the abstract methods specified below. The means by which a file type detector determines the file type is highly implementation specific. A simple implementation might examine the file extension (a convention used in some platforms) and map it to a file type. In other cases, the file type may be stored as a file attribute or the bytes in a file may be examined to guess its file type.
Constructor Summary
Method Summary
Methods declared in class java.lang.Object
Constructor Detail
FileTypeDetector
protected FileTypeDetector()
Method Detail
probeContentType
public abstract String probeContentType(Path path) throws IOException
Probes the given file to guess its content type. The means by which this method determines the file type is highly implementation specific. It may simply examine the file name, it may use a file attribute, or it may examines bytes in the file. The probe result is the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type as defined by RFC 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. The string must be parsable according to the grammar in the RFC 2045.
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Определение типов файлов в Java
Программно определить тип файла может быть удивительно сложно, и было предложено и реализовано много подходов идентификации файлов на основе контента . Существует несколько реализаций, доступных в Java для обнаружения типов файлов, и большинство из них в значительной степени или исключительно основаны на расширениях файлов. В этом посте рассматриваются некоторые из наиболее распространенных реализаций обнаружения типов файлов в Java.
В этом посте демонстрируется несколько подходов к идентификации типов файлов в Java. Каждый подход кратко описан, проиллюстрирован листингом кода, а затем связан с выводом, который демонстрирует, как различные общие файлы печатаются на основе расширений. Некоторые из подходов являются настраиваемыми, но все показанные здесь примеры используют сопоставления «по умолчанию», как это предусмотрено «из коробки», если не указано иное.
О примерах
Снимки экрана, показанные в этом посте, представляют собой каждый из перечисленных фрагментов кода, запускаемых для определенных тематических файлов, созданных для тестирования различных реализаций обнаружения типов файлов в Java. Прежде чем рассказать об этих подходах и продемонстрировать тип, который обнаруживает каждый из них, я перечисляю тестируемые файлы, их имена и имена.
файл название | файл расширение | файл Тип | Тип совпадений Конвенция о продлении? |
---|---|---|---|
actualXml.xml | XML | XML | да |
blogPostPDF | нет | ||
blogPost.pdf | да | ||
blogPost.gif | GIF | GIF | да |
blogPost.jpg | JPG | JPEG | да |
blogPost.png | PNG | PNG | да |
blogPostPDF.txt | текст | нет | |
blogPostPDF.xml | XML | нет | |
blogPostPNG.gif | GIF | PNG | нет |
blogPostPNG.jpg | JPG | PNG | нет |
dustin.txt | текст | Текст | да |
dustin.xml | XML | Текст | нет |
Дастин | Текст | нет |
Files.probeContentType (Path) [JDK 7]
Java SE 7 представила высоко утилитарный класс Files, и Javadoc этого класса кратко описывает его использование: «Этот класс состоит исключительно из статических методов, которые работают с файлами, каталогами или другими типами файлов» и «в большинстве случаев с методами, определенными здесь делегирует соответствующему провайдеру файловой системы для выполнения файловых операций ».
Класс java.nio.file.Files предоставляет метод probeContentType (Path), который «проверяет тип содержимого файла» посредством использования «установленных реализаций FileTypeDetector» (Javadoc также отмечает, что «данный вызов виртуальной машины Java») ведет общесистемный список детекторов типов файлов »).