Joe88
Joe88

Reputation: 441

Check file extension in Java

I have to import data from an Excel file to database and to do this, I would like to check the extension of the chosen file.

This is my code:

String filename = file.getName();
String extension = filename.substring(filename.lastIndexOf(".") + 1, filename.length());

String excel = "xls";
if (extension != excel) {
    JOptionPane.showMessageDialog(null, "Choose an excel file!");
}
else {
    String filepath = file.getAbsolutePath();
    JOptionPane.showMessageDialog(null, filepath);
    String upload = UploadPoData.initialize(null, filepath);

    if (upload == "OK") {
        JOptionPane.showMessageDialog(null, "Upload Successful!");
    }
}

But I always get:

Choose an excel file!

I can't find what is wrong with my code, could someone please help.

Upvotes: 29

Views: 55671

Answers (8)

Vitaly Vlasov
Vitaly Vlasov

Reputation: 95

In my programm i did that

if(file_name.endsWith(".xls") || file_name.endsWith(".xlsx"))
   // something works with file

Upvotes: 2

kevlaria
kevlaria

Reputation: 33

How about

if (filename.endsWith("xls"){
    <blah blah blah>
}

?

Upvotes: 0

Rajesh Pitty
Rajesh Pitty

Reputation: 2843

You can use Apache Commons Api to check the file extension

String filename = file.getName();
if(!FilenameUtils.isExtension(filename,"xls")){
  JOptionPane.showMessageDialog(null, "Choose an excel file!");
}

http://commons.apache.org/io/api-release/index.html?org/apache/commons/io/package-summary.html

Upvotes: 3

amicngh
amicngh

Reputation: 7899

if (extension != excel){
   JOptionPane.showMessageDialog(null, "Choose an excel file!");

}

should be used as

if (!extension.equals(excel)){
   JOptionPane.showMessageDialog(null, "Choose an excel file!");

}

And

 if (upload == "OK") {
 JOptionPane.showMessageDialog(null,"Upload Successful!");
}

as

 if ("OK".equals(upload)) {
 JOptionPane.showMessageDialog(null,"Upload Successful!");
}

Upvotes: 6

Jigar Joshi
Jigar Joshi

Reputation: 240946

following

extension != excel

should be

!excel.equals(extension)

or

!excel.equalsIgnoreCase(extension)

See also

Upvotes: 28

missingfaktor
missingfaktor

Reputation: 92106

== tests referentially equality. For value equality test, use .equals. Use String#equalsIgnoreCase if you want the case to be disregarded during the equality test.

Another thing: Don't reinvent the wheel, unless it's badly broken. In your case, you should be using Apache Commons' FilenameUtils#isExtension to check the extension.

Upvotes: 7

Pramod Kumar
Pramod Kumar

Reputation: 8014

use

excel.equals(extension)

or

excel.equalsIgnoreCase(extension)

Upvotes: 3

Chandra Sekhar
Chandra Sekhar

Reputation: 19500

use equals() method instead of != symbols in your case. I mean write

if (!(extension.equals(excel))){..........}

Upvotes: 1

Related Questions