Class ContentSniffer
java.lang.Object
com.iizix.util.ContentSniffer
Detects a file's media type from its leading bytes ("magic bytes"), independently of any name, extension or declared type.
The sniffer is deliberately small and deliberately strict: it knows a handful of binary formats whose first bytes are a fixed signature, and answers null for everything else. Text formats (SVG, XML, CSV, plain text) are never sniffed, because a byte prefix cannot prove them. A caller therefore treats null as "unknown to the sniffer", never as "not a file of the declared type".
Stateless and thread-safe; all methods are static.
- Author:
- Christopher Mindus
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intThe number of leading bytes the sniffer needs; more are ignored, fewer may still match a shorter signature.Method Summary
Modifier and TypeMethodDescriptionstatic booleanChecks if a media type is one the sniffer can recognize, i.e.static Stringsniff(byte[] head) Sniffs the media type from the leading bytes of a file.static Stringsniff(byte[] head, int length) Sniffs the media type from the leading bytes of a file.static Stringsniff(InputStream in) Reads the head of a stream and sniffs it.
Field Details
HEAD_LENGTH
public static final int HEAD_LENGTHThe number of leading bytes the sniffer needs; more are ignored, fewer may still match a shorter signature.- See Also:
Method Details
sniff
Sniffs the media type from the leading bytes of a file.- Parameters:
head- The leading bytes, at mostHEAD_LENGTHare looked at.length- The number of valid bytes inhead.- Returns:
- The media type in lower case, or null if no known signature matches.
- Throws:
NullPointerException- Ifheadis null.IllegalArgumentException- Iflengthis negative or exceeds the array.
sniff
Sniffs the media type from the leading bytes of a file.- Parameters:
head- The leading bytes; the whole array is valid.- Returns:
- The media type in lower case, or null if no known signature matches.
sniff
Reads the head of a stream and sniffs it. At mostHEAD_LENGTHbytes are consumed; the stream is not closed and is not reset.- Parameters:
in- The stream, positioned at the first byte of the content.- Returns:
- The media type in lower case, or null if no known signature matches.
- Throws:
IOException- For read errors.
isKnown
Checks if a media type is one the sniffer can recognize, i.e. one for which anullanswer fromsniff(byte[],int)means "the bytes are NOT of this type" rather than "unknown".- Parameters:
mediaType- The media type, case-insensitive, may be null.- Returns:
- true if the sniffer knows a signature for the type.