search
Login

Categories


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

3.8k questions

4k answers

117 comments

10.7k users

0 votes
38 views
asked Guru 24.6k points 29 51 75

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 Guru 27.1k points 31 47 92

Related questions

0 votes
1 answer 3.9K views
3.9K views
I am looking to use Java to get the MD5 checksum of a file. I was really surprised but I haven't been able to find anything that shows how to get the MD5 checksum of a file. How is it done?
asked sara Guru 24.6k points 29 51 75
0 votes
2 answers 21 views
21 views
asked sara Guru 24.6k points 29 51 75
0 votes
1 answer 22 views
22 views
asked smith Geek 15.3k points 14 39 58
0 votes
1 answer 24 views
24 views
I started using JSF 2.0 with Facelets recently and got puzzled by new composite components knowing existing <ui:include> and other templating techniques offered by Facelets 1.x.
asked john Guru 27.1k points 31 47 92
0 votes
2 answers 23 views
23 views
asked john Guru 27.1k points 31 47 92
...