在Java中检查文件类型(CSV或Excel文件(XLSX))

3hvapo4f  于 2023-06-19  发布在  Java
关注(0)|答案(2)|浏览(347)

我需要上传一个文件。在我上传之前,我需要知道文件是csv还是excel文件(xlsx)。如果是csv或excel文件,我将继续否则退出。我如何知道在java中的文件的类型通过使用其路径。

irlmq6kh

irlmq6kh1#

你可以使用probeContentType(Path path)来实现。
探测文件的内容类型。
如果content-typetext/csv,则它是.csv文件。如果content-typeapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet,则是.xlsx文件。
你应该尝试这样的做法:

File file = new File("some path");
Path filePath = file.toPath();
String contentType = probeContentType(filePath);
if("text/csv".equals(contentType)) { 
  ...
}
zbdgwd5y

zbdgwd5y2#

<?php
  $mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
    if(in_array($_FILES['file']['type'],$mimes)){
      // do something
    } else {
      die("Sorry, mime type not allowed");
    }

?>

相关问题