用Java检查文件扩展名

我必须将数据从Excel文件导入数据库并执行此操作,我想检查所选文件的扩展名。

这是我的代码:

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!"); } } 

但我总是得到:

选择一个excel文件!

我找不到我的代码有什么问题,请有人帮忙。

以下

 extension != excel 

应该

 !excel.equals(extension) 

要么

 !excel.equalsIgnoreCase(extension) 

也可以看看

  • 字符串equals()==

==测试参考平等。 对于值相等测试,请使用.equals 。 如果希望在相等测试期间忽略大小写,请使用String#equalsIgnoreCase

另一件事:不要重新发明轮子,除非它被严重破坏。 在您的情况下,您应该使用Apache Commons的FilenameUtils#isExtension来检查扩展名。

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

应该用作

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

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

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

使用

 excel.equals(extension) or excel.equalsIgnoreCase(extension) 

您可以使用Apache Commons Api检查文件扩展名

 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

在您的情况下使用equals()方法而不是!=符号。 我是说写

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

怎么样

 if (filename.endsWith("xls"){  } 

在我的程序中,我做到了

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