方式一:识别后缀
方式二:FileMagic
public static void main(String[] args) throws Exception {
String inPath = "x.doc/x.docx";
InputStream is = new BufferedInputStream(new FileInputStream(inPath));
if(FileMagic.valueOf(is) == FileMagic.OLE2){
HWPFDocument doc= new HWPFDocument(new FileInputStream(inPath));
}else if(FileMagic.valueOf(is) == FileMagic.OOXML){
XWPFDocument docx = new XWPFDocument(new FileInputStream(inPath));
}else{ //其他
}
is.close();
}
方式三:识别zip/异常解析
public static void main(String[] args) {
String inPath = "x.doc/x.docx";
try {
//docx
new ZipFile(new File(inPath));
} catch (Exception e) {
//doc
e.printStackTrace();
}
}