Search code examples
javafileends-with

Detect a File Extension in Java


I'm trying to detect if the file that I am opening is a HTML file.

I have already tried this:

try {
   String file = fileName.getCanonicalPath();

   if (file.endsWith(".htm") | file.endsWith(".html")) {

   }

   } catch (IOException e) {
       e.printStackTrace();
   }

But the file.endsWith(); doesn't seem to be detecting anything. The fileName is the file that I'm opening. Let me know if I have to post the code that I use to open the file.

Thanks in advance.


Solution

  • This line looks suspect:

    if (file.endsWith(".htm") | file.endsWith(".html")) {
    

    The | operator is the bitwise-OR operator. You need the logical-OR operator, ||.

    EDIT

    Adding what @MadProgrammer suggessted in a comment:

    Call toLowerCase() on the filename to account for the possibility that the file ends in .HTM or .HTML.