C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers

114 comments

10,705 users

Getting A File's Mime Type In Java?

0 votes
37 views
asked Jan 24, 2014 by sara Guru (24,570 points)

1 Answer

0 votes
Unfortunately,
 
mimeType = file.toURL().openConnection().getContentType();
does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.
 
However, you have this:
 
mimeType= URLConnection.guessContentTypeFromName(file.getName());
and also the following, which has the advantage of going beyond mere use of file extension, and takes a peek at content
 
InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
 //...close stream
However, as suggested by the comment above, the built-in table of mime-types is quite limited, not including, for example, MSWord and PDF. So, if you want to generalize, you'll need to go beyond the built-in libraries, using, e.g., Mime-Util (which is a great library, using both file extension and content).
 
 
answered Jan 24, 2014 by john Guru (27,140 points)

Related questions

0 votes
1 answer 3,905 views
3,905 views asked Jan 29, 2014 by sara Guru (24,570 points)
0 votes
2 answers 18 views
18 views asked Jan 2, 2014 by sara Guru (24,570 points)
0 votes
1 answer 21 views
21 views asked Jan 3, 2014 by smith Geek (15,340 points)
0 votes
1 answer 22 views
0 votes
2 answers 21 views
21 views asked Jan 20, 2014 by john Guru (27,140 points)
...