2

I am very confused by this comparison with FilenameUtils.getExtension.

I have a file chooser fc that I want to ensure that the extension is .csv.

JFileChooser fc = new JFileChooser();
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION &&
    fc.getSelectedFile().isFile() &&
    FilenameUtils.getExtension(fc.getSelectedFile().getName()) == "csv") {
    // Do stuff
}

After some debugging, I found that the last statement was responsible for not having the if statement executed.

FilenameUtils.getExtension(fc.getSelectedFile().getName()) == "csv"

However I did many System.out.println()s and got that

System.out.println(FilenameUtils.getExtension(fc.getSelectedFile().getName()));

Prints csv. But still returns false when I enter:

System.out.println(FilenameUtils.getExtension(fc.getSelectedFile().getName()) == "csv");
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38

2 Answers2

6

You can't compare the content of Strings with ==. You'll have to use the equals(...) method for that:

System.out.println(FilenameUtils.getExtension(fc.getSelectedFile().getName()).equals("csv"));
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
6

The Problem your facing is and well known one. You are trying to compare Strings with the ==-operator. Instead of that you should use the equals-function of String.

There is a little difference between you those two ways: If you want you can read this question and there answers to see the difference between both.

Applied to that code it should look like that:

System.out.println(FilenameUtils.getExtension(fc.getSelectedFile().getName()).equals("csv"));

Hope that helps!

Community
  • 1
  • 1
Felix Gerber
  • 1,615
  • 3
  • 30
  • 40