在java中检查文件的类型(csv或excel文件(xlsx))

时间:2015-12-24 05:40:39

标签: java excel csv

我需要上传文件。在我上传它之前,我需要知道该文件是csv还是excel文件(xlsx)。如果是csv或excel文件,我会继续退出。 如何通过使用其路径来了解java中文件的类型。

2 个答案:

答案 0 :(得分:3)

您可以使用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)) { 
  ...
}

答案 1 :(得分:-1)

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