0

I am writing a program that, given a file consisting of words and associated objects, creates a dictionary. For instance, I may have the word "Apple" associated with the String object "A red fruit"

Now, some of the objects are image files, and some are audio files. Of the image files, only the extensions ".jpg" and ".gif" will be considered (i.e. included in the file). Likewise, for the audio files, only ".wav" and ".mid" will be considered.

I have classes to handle displaying the image files and playing the audio files already, but I am now trying to figure out (when inputting the information) how to detect if an object is an image or audio file, or if it is neither. I was thinking of somehow checking the last three characters of the object, so for instance if it is "jpg" then I would mark it as an image type object. Or, if it was "uit" as in the "Apple" example above, then it would be marked as neither. However, I don't know how to check only the last three characters of a string. Is there some built-in method to do this String check automatically?

  • 1
    http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#endsWith(java.lang.String) ? –  Nov 18 '12 at 05:37
  • 1
    use `endsWith()` function to check whether it ends with a particular string. – Shashank Kadne Nov 18 '12 at 05:37
  • see also: http://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java if you want to check without extension –  Nov 18 '12 at 05:38

2 Answers2

0

Checking the last 3 characters of the file name is not a good way, I think. You can check the characters starting from the last index of '.' (dot) just like in this utility method:

public static String getFileExtension(String fileName) 
{
    if (fileName == null || fileName.equals("") || !fileName.contains("."))
        return "";

    return fileName.substring(fileName.lastIndexOf('.'), fileName.length());
}
Juvanis
  • 25,802
  • 5
  • 69
  • 87
0

Checking the extension of a file is not a good way to find the type of it.

I had a very similar situation and after a while I figured out that the best way is to check the mimeType. I myself use mimemagic. Here you may find more about it.

Matin Kh
  • 5,192
  • 6
  • 53
  • 77