This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is indexof only way of identify in file type

 
Gaurav Chikara
Ranch Hand
Posts: 412
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All
While making a fileinputstream in case we have to check for file type for enforcing validation rule. Is there any better way except doing an indexOf on File complete path.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would use the endsWith() method instead, to avoid the possibility that a file extension might also occur elsewhere in the path.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jim Yingst:
I would use the endsWith() method instead, to avoid the possibility that a file extension might also occur elsewhere in the path.


I would do a getName() on file object and then endsWith()
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are wanting to check whether a given file is of the right content type, you may want to look at URLConnection.guessContentTypeFromName() and URLConnection.guessContentTypeFromStream().

Note you can make a URL from a File.
 
Gaurav Chikara
Ranch Hand
Posts: 412
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you may want to look at URLConnection.guessContentTypeFromName() and URLConnection.guessContentTypeFromStream().

It seems to be a good solution but is it possible to get URLConnection somehow from request object as I must be doing this check in struts kind of framework where we only have request object to get most of the input
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
URLConnection.guessContentTypeFromName() and -Stream() are static methods, so you don't need an instance. You should be able to call these anywhere.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can call them without an instance of URLConnection. My code does it: -

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic