2

I'm writing a program, and the have to select an excel file, that will be read by the program. My question is now, how can I prove, if the file is an excel file or not?.

The file is selected in this method:

JButton btnFile = new JButton("Select Excel File");
btnFile.setPreferredSize(new Dimension(40, 40));
btnFile.addActionListener(new ActionListener() {
    // Handle open button action.
    public void actionPerformed(ActionEvent e) {
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(frame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            // This is where a real application would open the file.
            System.out.println("File: " + file.getName() + ".");
        } else {
            System.out.println("Open command cancelled by user.");
        }
        System.out.println(returnVal);
    }
});
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Phil
  • 87
  • 1
  • 1
  • 9

5 Answers5

9

MimetypesFileTypeMap.getContentType(String) [JDK 6]

The class MimetypesFileTypeMap was introduced with Java SE 6 to provide "data typing of files via their file extension" using "the .mime.types format." The class's Javadoc explains where in a given system the class looks for MIME types file entries. My example uses the ones that come out-of-the-box with my JDK 8 installation. The next code listing demonstrates use of javax.activation.MimetypesFileTypeMap.

public String identifyFileTypeUsingMimetypesFileTypeMap(final String fileName)  
{      
   final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();  
   return fileTypeMap.getContentType(fileName);  
} 

Files.probeContentType(Path) [JDK 7]

Java SE 7 introduced the highly utilitarian Files class and that class's Javadoc succinctly describes its use: "This class consists exclusively of static methods that operate on files, directories, or other types of files" and, "in most cases, the methods defined here will delegate to the associated file system provider to perform the file operations."

The java.nio.file.Files class provides the method probeContentType(Path) that "probes the content type of a file" through use of "the installed FileTypeDetector implementations" (the Javadoc also notes that "a given invocation of the Java virtual machine maintains a system-wide list of file type detectors").

public String identifyFileTypeUsingFilesProbeContentType(final String fileName)  
{  
   String fileType = "Undetermined";  
   final File file = new File(fileName);  
   try  
   {  
      fileType = Files.probeContentType(file.toPath());  
   }  
   catch (IOException ioException)  
   {  
      out.println(  
           "ERROR: Unable to determine file type for " + fileName  
              + " due to exception " + ioException);  
   }  
   return fileType;  
}  

For more details please visit this link

Community
  • 1
  • 1
Bacteria
  • 8,406
  • 10
  • 50
  • 67
2

Check for the file extension 'xlsx' in the file name. However, to validate whether the selected file is actually an excel file,you need a library to validate such as Apache POI HSSF. Refer this answer for more information.

Community
  • 1
  • 1
K139
  • 3,654
  • 13
  • 17
2

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

You can also do something Like this.You will have to check for all the file types you are considering.I am just providing you the direction in which you should think :

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

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

    }
    else {
        String filepath = file.getAbsolutePath();
        JOptionPane.showMessageDialog(null, filepath);
        String upload = UploadPoData.initialize(null, filepath);

         if ("OK".equals(upload)) {
     JOptionPane.showMessageDialog(null,"Upload Successful!");
    }
    }
Naveen Goyal
  • 446
  • 1
  • 3
  • 12
1

I agree with K139 and UUIIUI answers but just for information you can use as well a framework like tika for this kind of control.

Aurelien
  • 458
  • 1
  • 5
  • 13
0

You can add a filter to the filechooser that only makes it possible to chose .xlsx files (you can add more extensions by using OR in the return with another extension)

    fc = new JFileChooser();

    fc.setFileFilter(new FileFilter() {

      public String getDescription() {
          return "Excel Documents (.xlsx)";
      }

      public boolean accept(File f) {
          if (f.isDirectory()) {
              return true;
          } else {
              String filename = f.getName().toLowerCase();
              return filename.endsWith(".xlsx") ;
          }
      }
   });
asiew
  • 493
  • 4
  • 13
  • Of course, we can't say this is wrong. But this program won't show error if a text file (.txt) is just renamed as xlsx file. Finding the mimetype is better way or throwing exception / catch exception when trying to run `WorkbookFactory.create(inputStream);` – smilyface Feb 08 '22 at 11:27