Check file extension in Java

后端 未结 8 872
深忆病人
深忆病人 2021-01-01 10:39

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          


        
相关标签:
8条回答
  • 2021-01-01 10:47

    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

    0 讨论(0)
  • 2021-01-01 10:52

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

    if (!(extension.equals(excel))){..........}
    
    0 讨论(0)
  • 2021-01-01 10:53

    How about

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

    ?

    0 讨论(0)
  • 2021-01-01 10:54

    == 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.

    0 讨论(0)
  • 2021-01-01 10:57

    use

    excel.equals(extension)
    
    or
    
    excel.equalsIgnoreCase(extension)
    
    0 讨论(0)
  • 2021-01-01 10:58
    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!");
    }
    
    0 讨论(0)
提交回复
热议问题