栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现DOC文件转DOCX文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java实现DOC文件转DOCX文件

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


    e-iceblue
    spire.doc.free
    3.9.0




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.*;



public class MDocTest {

    public static void main(String[] args) throws Exception {
        String srcfile = "D:\核工业口述史(编辑稿)0423_妇女出版社2.doc";
        ByteArrayToFile(convertDocIs2DocxIs( new FileInputStream(new File(srcfile))),"D:\核工业口述史(编辑稿)0423_妇女出版社33.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;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/305890.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号