Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Is indexof only way of identify in file type  RSS feed

 
Ranch Hand
Posts: 413
  • 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.
 
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.
 
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()
 
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: 413
  • 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: -

 
Let's go to the waterfront with this tiny ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!