java 实现doc 转 docx,打开出现文件格式与扩展名不匹配错误,解决方案

弯路

使用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包下载地址

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值