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");
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!
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With