弯路
使用poi库
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.WordToHtmlUtils;
import java.io.*;
public class FileUtil2 {
public static void convertDocToDocx(String docPath, String docxPath) {
try {
File file = new File(docPath);
File docxFile = new File(docxPath);
HWPFDocumentCore doc = WordToHtmlUtils.loadDoc(file);
doc.write(docxFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
try {
convertDocToDocx("D:/imagepool/doc/测试文档0102.doc", "D:/imagepool/doc/测试文档0102.docx");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
问题
上面操作有问题,只是改了后缀名,并没有对文件格式进行转换,有的文件转换成功,打开正常,有的打开出现文件格式与扩展名不匹配错误,如下图所示,请使用下面的方法。
正道
<dependency>
<groupId>com.luhuiguo</groupId>
<artifactId>aspose-words</artifactId>
<version>18.2</version>
<scope>system</scope>
<systemPath>${pom.basedir}/lib/aspose-words-18.2-jdk16.jar</systemPath>
</dependency>
public static void doc2docx(String docFile, String docxFile) {
com.aspose.words.Document doc;
try {
String tempFile = docxFile.substring(0, docxFile.lastIndexOf(".")) + "_temp"
+ docxFile.substring(docxFile.lastIndexOf("."), docxFile.length());
doc = new com.aspose.words.Document(docFile);
doc.save(tempFile);
Map<String, String> map = new HashMap<String, String>();
map.put("Evaluation Only. Created with Aspose.Words. Copyright 2003-2018 Aspose Pty Ltd.", "");
// 使用 aspose不使用license.xml会产生,替换水印的文字
DocxReplace.replaceAndGenerateWord(tempFile, docxFile, map);
// 删除临时文件
forceDelete(new File(tempFile));
} catch (Exception e1) {
e1.printStackTrace();
}
}
public static boolean forceDelete(File file) {
boolean result = file.delete();
int tryCount = 0;
while (!result && tryCount++ < 10) {
System.gc();
result = file.delete();
}
return result;
}
调用
// 文件转换
String docPath = "./测试.doc";
String docxPath = "./测试.docx";
doc2docx(docPath , docxPath );
// 删除doc 文件
forceDelete(new File(docPath ));
jar文件免费下载链接:jar包下载地址