3

Is it possible to get content type/mime type of a file from the file read as a stream from its stored location.

I am bit new to the file and stuffs, I was searching all day long but couldn't get what i have needed.

please help me out of this. thanks in advance

Edit:- Edit:

Guys thanks for your comments.

My java version is 6 and i can't trust the filename to get its mime type.

Muthurathinam
  • 962
  • 2
  • 11
  • 19
  • 2
    http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType(java.nio.file.Path) - Use probeContentType() – user1428716 Apr 25 '15 at 14:46

4 Answers4

5

Use this:

Files.probeContentType(path)

By the way your question is a duplicate of this SO post. Please check SO thoroughly before asking your next question.

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • thanks for ur comment. but real bottleneck is, i have got java version 6 and can't trust the filename. any help would be appreciated.. – Muthurathinam Apr 25 '15 at 15:26
  • Use the `MimeTypes` open source class from the Servoy project. See [this link](https://github.com/Servoy/servoy-client/blob/e7f5bce3c3dc0f0eb1cd240fce48c75143a25432/servoy_shared/src/com/servoy/j2db/util/MimeTypes.java#L34) for more details. This will run on Java 6. – Tim Biegeleisen Apr 25 '15 at 15:31
3

A MIME type of a file is not part of the file itself. Rather, it is typically configured and provided by the server from which the file is accessed; through an HTTP header for example. Some binary files have what are called "magic numbers" which can, to some degree, be used to identify the contents of the file. See here for a catalog of common ones. For example, you may be able to look at the first few bytes of the file stream and check the catalog to determine the type. However, there is no guarantee that this method will be accurate.

As others have suggested, you can use Files#probeContentType(), but that takes a file name. If you only have access to a stream, your out-of-luck. Also, it too suffers from the same accuracy issues.

pathfinderelite
  • 3,047
  • 1
  • 27
  • 30
1

From Java Docs : http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType(java.nio.file.Path)

Use

probeContentType()

user1428716
  • 2,078
  • 2
  • 18
  • 37
1

Maybe this link will help:

mime type of files

Sunny Das
  • 91
  • 1
  • 3