Checking files / getting true file type in Java / Groovy?

I need to determine if a file has a given set of true types, and I was wondering how best to do this.

Essentially, I really need to check only PDF files, images, and some types of Microsoft Word files. I heard about using imagemagick and exceptions for testing images, but what about others?

Any ideas?

+3
source share
3 answers

There are several ways to get the MIME type on this page.

MIME , , , Apache Tika framework, .

Tika ( Groovy):

// Grab tika and all its dependencies...
// takes a while on first run, as it pulls in LOADS of dependencies
@Grab( 'org.apache.tika:tika-core:0.9' )
@Grab( 'org.apache.tika:tika-parsers:0.9' )
import org.apache.tika.Tika

println( new Tika().detect( new File( 'tim.tiff' ) ) )
println( new Tika().detect( new File( 'tim.renamedtiff' ) ) )

:

15:15:56 [tim_yates@mac] TikaTest $ groovy test.groovy 
image/tiff
image/tiff
+5

MimetypesFileTypeMap groovy:

import javax.activation.MimetypesFileTypeMap

String contentType = new MimetypesFileTypeMap().getContentType("foo.gif")
println contentType

: image/gif

+1
file.toURL().openConnection().getContentType()

A file is an instance of java.io.File

What is it!

0
source

All Articles