java 如何检查文件是否为excel文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34398075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if the file is an excel file?
提问by Phil
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?.
我正在编写一个程序,必须选择一个excel文件,该文件将由程序读取。我现在的问题是,我如何证明文件是否是 excel 文件?。
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);
}
});
采纳答案by asiew
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)
您可以向文件选择器添加一个过滤器,该过滤器只能选择 .xlsx 文件(您可以通过在返回中使用 OR 添加更多扩展名和另一个扩展名)
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") ;
}
}
});
回答by Bacteria
MimetypesFileTypeMap.getContentType(String) [JDK 6]
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.
MimetypesFileTypeMap 类是在 Java SE 6 中引入的,以使用“.mime.types 格式”提供“通过文件扩展名对文件进行数据类型化”。该类的 Javadoc 解释了该类在给定系统中查找 MIME 类型文件条目的位置。我的示例使用我的 JDK 8 安装开箱即用的那些。下一个代码清单演示了 javax.activation.MimetypesFileTypeMap 的使用。
public String identifyFileTypeUsingMimetypesFileTypeMap(final String fileName)
{
final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
return fileTypeMap.getContentType(fileName);
}
Files.probeContentType(Path) [JDK 7]
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").
Java SE 7 引入了高度实用的 Files 类,该类的 Javadoc 简洁地描述了它的用途:“这个类完全由对文件、目录或其他类型文件进行操作的静态方法组成”和“在大多数情况下,这里定义的方法将委托给关联的文件系统提供程序来执行文件操作。”
java.nio.file.Files 类提供了通过使用“已安装的 FileTypeDetector 实现”来“探测文件的内容类型”的方法 probeContentType(Path)(Javadoc 还指出“Java 虚拟机的给定调用维护一个系统范围的文件类型检测器列表”)。
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
有关更多详细信息,请访问此链接
回答by K139
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.
检查文件名'xlsx'
中的文件扩展名。但是,要验证所选文件是否实际上是 excel 文件,您需要一个库来验证,例如 Apache POI HSSF。有关更多信息,请参阅此答案。
回答by Naveen Goyal
You can use Apache Commons Api to check the file 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
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!");
}
}