0

I was wondering if there is a simple way in Java to know which category of file a file can be (video, audio, document, simple text, ...).

I have tried to know by looking the extension, but I think there is an easier way, is it ??

I'm looking forward for your comment.

2 Answers2

0

You may want to take a look at How to reliably detect file types? (especially this answer).

I would suggest you to study if it your need allows the usage of Java's FileTypeDetector class.

Community
  • 1
  • 1
Bruno Toffolo
  • 1,504
  • 19
  • 24
-1

There is a native package from java called java.nio.file.spi can do this for you ! As per the documentation, it will guess the type of the file by two ways by extensions and by examining the bytes. Have a look to the documentation : Official docs for File Type Detector

As per the discussion in the comment, I am enhancing this answer with this superb next step : Take a look in this segment : ( probeContentType >>)

public static String probeContentType(Path path)
                           throws IOException
Sagiruddin Mondal
  • 5,407
  • 2
  • 29
  • 44
  • Thanks a lot, it helped a lot !! – programminator Mar 28 '16 at 17:08
  • The proper way to use this is not to use the spi package. The only way anyone should be using this is with the [Files.probeContentType](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#probeContentType-java.nio.file.Path-) method (to which that spi documentation links, fortunately). – VGR Mar 28 '16 at 17:30
  • Yes ! You are right. But I have told the native and first step into it. There can be so many use cases for that and probeContentType is definitely helpful. Thanks @VGR – Sagiruddin Mondal Mar 28 '16 at 17:36