java執行命令並通過libreoffice軟件的方式將word轉化成HTML的詳細步驟解析


 

一、實現代碼 :

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 將word文檔通過java調用命令的方式轉化成HTML
 */
public class DocConvertDemo {
    public static void main(String[] args) throws IOException {
        /**
         * D:\soft\LibreOffice_6.0.6\program\soffice:表示libreoffice安裝路徑
         * D:\Desktop\DocCloud\testDir\hadoopInstall.doc:表示要轉化的word文件
         */
        String fileName= "D:\\Desktop\\DocCloud\\testDir\\hadoopInstall.doc";
        String command = "D:\\soft\\LibreOffice_6.0.6\\program\\soffice --headless --invisible --convert-to html "+fileName;
        /**
         *workDir:表示轉化之后的HTML文件保存的路徑地址
         */
        String workDir = "D:\\tmp\\doccloud-Administrator\\.stage\\"+UUID.randomUUID().toString()+"\\";
        File file = new File(workDir);
        //創建目錄--因為是UUID所以不用判斷目錄一定不存在
        file.mkdirs();
        /**
         * command:命令
         * null:操作系統運行程序時通過envp 參數將系統環境變量傳遞給程序
         * file:命令在那個路徑下執行
         */
        //返回過程對象--Process
        Process exec = Runtime.getRuntime().exec(command,null,file);
        //錯誤信息
        InputStream errorStream = exec.getErrorStream();
        //結果信息
        InputStream inputStream = exec.getInputStream();
        //IOUtils-直接將流轉化成字符串
        String error = IOUtils.toString(errorStream);
        String result = IOUtils.toString(inputStream);
        //打印信息
        System.out.println(error);
        System.out.println(result);
    }
}

二、測試結果

控制台

 磁盤上

HTML打開內容如下(不同文件內容不同):


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM