Java实现DOC文件转DOCX文件

1.文件较小少于500段,使用spire.doc.free转化

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc.free</artifactId>
    <version>3.9.0</version>
</dependency>



Document document = new Document();
document.loadFromFile("源文件路径");
document.saveToFile("目标文件的路径", FileFormat.Docx);

2.文件较大利用aspose进行转换

package com.ruoyi;

import com.aspose.words.SaveFormat;
import org.springframework.util.FileCopyUtils;

import java.io.*;

/**
 * @program: ruoyi
 * @create: 2021-10-08 11:33
 * @author: sxl
 * @description:
 **/

public class MDocTest {

    public static void main(String[] args) throws Exception {
        String srcfile = "D:\\aaa.doc";
        ByteArrayToFile(convertDocIs2DocxIs( new FileInputStream(new File(srcfile))),"D:\\bbb.docx") ;
    }
    // 字节数组到文件的过程
    public static void ByteArrayToFile(byte[] data,String newFileNmae) {
        File file = new File(newFileNmae);
        //选择流
        FileOutputStream fos = null;
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(data);
            fos = new FileOutputStream(file);
            int temp;
            byte[] bt = new byte[1024*10];
            while((temp = bais.read(bt))!= -1) {
                fos.write(bt,0,temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关流
            try {
                if(null != fos)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 将doc输入流转换为docx输入流
    private static byte[] convertDocIs2DocxIs(InputStream docInputStream) throws IOException {
        byte[] docBytes = FileCopyUtils.copyToByteArray(docInputStream);
        byte[] docxBytes = convertDocStream2docxStream(docBytes);
        return docxBytes;
    }
    // 将doc字节数组转换为docx字节数组
    private static byte[] convertDocStream2docxStream(byte[] arrays) {
        byte[] docxBytes = new byte[1];
        if (arrays != null && arrays.length > 0) {
            try (
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    InputStream sbs = new ByteArrayInputStream(arrays)
            ) {
                com.aspose.words.Document doc = new com.aspose.words.Document(sbs);
                doc.save(os, SaveFormat.DOCX);
                docxBytes = os.toByteArray();
            } catch (Exception e) {
                System.out.println("出错啦");
            }
        }
        return docxBytes;
    }
}

  • 4
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值