Skip to content

Detects MIME type of file, byte array, or input stream. Written in Kotlin

Notifications You must be signed in to change notification settings

alekseinovikov/KTypeParser

Repository files navigation

KTypeParser

Build Status BUILD (Ubuntu 20.04)

Description

The parser determines a type of a file, byte array or input stream.

Build

You can build the project using Gradle.

Usage

Add dependency into your Gradle project:

repositories {
    ...

    maven {
        url  "https://dl.bintray.com/alekseinovikov/KTypeParser"
    }

    ...
}

dependencies {
    ...

    implementation 'org.ktypeparser:ktype-parser:2.1'
    
    ...
}

Functions:

  • detect(inputStream: InputStream): MediaType?

  • detect(bytes: ByteArray): MediaType?

  • detect(file: File): MediaType?

  • suspend fun detectAsync(inputStream: InputStream): Deferred<MediaType?>

  • suspend fun detectAsync(bytes: ByteArray): Deferred<MediaType?>

  • suspend fun detectAsync(file: File): Deferred<MediaType?>

Extension functions:

  • File.detectMediaType(): MediaType?

  • ByteArray.detectMediaType(): MediaType?

  • InputStream.detectMediaType(): MediaType?

  • suspend File.detectMediaTypeAsync(): Deferred<MediaType?>

  • suspend ByteArray.detectMediaTypeAsync(): Deferred<MediaType?>

  • suspend InputStream.detectMediaTypeAsync(): Deferred<MediaType?>

MediaType - is an enum with media types that can be determined by MIME Type

MediaType has field superType that is MediaSuperType. It represents short classification of the MediaTypes like:

  • OTHER
  • TEXT
  • IMAGE
  • AUDIO
  • VIDEO
  • APPLICATION

Extension functions and coroutines are in upcoming changes plans

Code example:

    val stream: InputStream = ByteArray::javaClass.javaClass.classLoader.getResourceAsStream("download.png")
    val streamMediaType = stream.detectMediaType()

    println(streamMediaType) //PNG
    println(streamMediaType.superType) //IMAGE

    val bytes: ByteArray = ByteArray::javaClass.javaClass.classLoader.getResourceAsStream("download.png").readAllBytes()
    val bytesMediaType = bytes.detectMediaType()

    println(bytesMediaType) //PNG
    println(bytesMediaType.superType) //IMAGE

    val file: File = File(ByteArray::javaClass.javaClass.classLoader.getResource("download.png").toURI())
    val fileMediaType = file.detectMediaType()

    println(fileMediaType) //PNG
    println(fileMediaType.superType) //IMAGE

Details

Using: https://github.com/overview/mime-types to detect mime-types as strings Classifies to a known enum values