Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FilenameUtils.getExtension comparison returns false [duplicate]

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");
like image 237
Moon Cheesez Avatar asked Mar 23 '26 00:03

Moon Cheesez


2 Answers

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!

like image 60
Felix Gerber Avatar answered Mar 24 '26 12:03

Felix Gerber


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"));
like image 42
ParkerHalo Avatar answered Mar 24 '26 14:03

ParkerHalo