File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes Checking File Type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Checking File Type" Watch "Checking File Type" New topic

Checking File Type

Awais Bajwa
Ranch Hand

Joined: Jan 16, 2001
Posts: 191

I am uploading a file, how can I ensure that the file being uploaded is only in text format. i.e if the user changes the file extension of exe to txt, still then , my program should point out that this file is not a txt it is an exe. any one have any idea.

My requiremtn is to allow only txt,html or image files.

Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
For text files you can check that the file does not contain any characters that are not part of the character sets you want to allow. Often that means only characters below 256 are allowed, but Uncode (or whatever other encoding might be used) complicate the matter a bit.

HTML files should have a DOCTYPE declaration at the beginning, although not all do.

You can test for image files of a particular type by something like the ImageInfo class.
Awais Bajwa
Ranch Hand

Joined: Jan 16, 2001
Posts: 191
Thanks for your post, I believe there must be some all in one utility to accomplish the task. I am already using Jakarta Common, may be this requiremetn is already present in the Commons.. i need to check.

Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

One utility to identify file types by looking at the contents? After you look at this extremely comprehensive site you may think differently. There are a LOT of different file types, as you will see by browsing that site a bit, and the vast majority of them don't have a documented format that can be used to identify them. But you could certainly scratch the surface and attempt to identify some of the more common formats.
I agree. Here's the link:
subject: Checking File Type
It's not a secret anymore!