Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

checking file extension  RSS feed

 
Susilo Saja
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, how can I check if the extension of a file is valid?
What I mean is, someone could just change the extension of a file to an invalid one. Or the file might be corrupted.
And if it's not valid, how can I know the real extension?
I need to do this with Java code.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your concept of "valid file extension" is pretty vague and open-ended, and obviously platform-dependent; only Microsoft has a formal concept of an extension. Still, I understand what you mean, so I'll talk about this for a minute.
Pretty much all you can do is make a list of extensions you're interested in, and then figure out your "validity criterion" for each one. For example, .java files contain only ASCII characters; .class files start with 0xCAFEBABE; GIF files start with "GIF"; .exe files start with "MZ", etc. Then you'll need to write some code to look up the criteria for a given extension and check it. If you've got only a few types of interest, a chain of if... then statements would work; otherwise, you might define a "CheckExtension" interface with implementations for each file type of interest, and put them in a HashMap keyed by the extension.
Note that some UNIX systems include a file named "magic" that lists distinguishing starting characters for many file types; these are called "magic numbers" and are often used to distinguish file types in lieu of extensions.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!