我正在编写一个程序,必须选择一个 excel 文件,该文件将由程序读取。我现在的问题是,我如何证明文件是否是 excel 文件?
该方法选择文件:
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);
}
});
最佳答案
MimetypesFileTypeMap.getContentType(字符串) [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(路径) [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;
}
更多详情请访问此link
关于java - 如何检查文件是否为excel文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34398075/