1

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.

user2228462
  • 589
  • 1
  • 5
  • 14
  • Do you really need the canonical path? http://stackoverflow.com/questions/1099300/whats-the-difference-between-getpath-getabsolutepath-and-getcanonicalpath – dnault May 08 '13 at 23:17

2 Answers2

4

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 1
    I'd also add `file.toLowerCase().endsWith` to ensure that you don't run into case comparison issues +1 none the less – MadProgrammer May 08 '13 at 22:23
  • @MadProgrammer - Good point, it could be ".HTM" for all we know. – rgettman May 08 '13 at 22:24
  • 2
    -1, the bitwise `|` works fine, it just doesn't have the short circuit feature. – jlordo May 08 '13 at 22:26
  • 1
    How would this solve the issue? Using `|` makes the second boolean expression evaluated regardless what the first expression returns. – Eng.Fouad May 08 '13 at 22:27
  • It works. I over-thought it. Although, I did move it around in my code. I'm not sure what caused it to work, but I'll accept your answer nonetheless. – user2228462 May 08 '13 at 22:30
  • @jlordo, I never expected `|` to work here. But I just tested `true | false` and `true & false` and they work as would be expected. I still think that `||` should be used here. – rgettman May 08 '13 at 22:32
  • @rgettman: I agree that using `a || b` is to be preferred over `a | b` unless you really need `a` _and_ `b` evaluated. But this won't solve OPs problem at all... – jlordo May 08 '13 at 22:47
2

You might have a case issue here as well. As @rgettman points out you probably need a logical or in there too

if (file.toLowerCase().endsWith(".htm") || file.toLowerCase().endsWith(".html")) {
RNJ
  • 15,272
  • 18
  • 86
  • 131