注意:此片短文僅用於個人的日常技術札記,在網上學習的,分享給大家,貢獻給在一線開發程序的java從業人員~
使用excel文檔轉成IMG文件時,用到了open office,中間一直存在文件找不到的問題:java.io.IOException: Cannot run program "C:\Program": CreateProcess error=2
這一部將在程序中以線程啓動的形式實現,不需要額外做調用系統的cmd窗口啓動服務。
程序中將實現將該服務啓動並在完成所有操作之後關閉服務。也就是說,每次執行改程序都會經過服務啓動與服務關閉的過程。如果你覺得這樣子對於系統性能有影響,你也可以單獨地啓動該openoffice服務。
三、 程序代碼
package com.sheke.wenku;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
public class Office2PDF {
/**
* 將Office文檔轉換爲PDF. 運行該函數需要用到OpenOffice, OpenOffice下載地址爲
* http://www.openoffice.org/
*
* <pre>
* 方法示例:
* String sourcePath = "F:\\office\\source.doc";
* String destFile = "F:\\pdf\\dest.pdf";
* Converter.office2PDF(sourcePath, destFile);
* </pre>
*
* @param sourceFile
* 源文件, 絕對路徑. 可以是Office2003-2007全部格式的文檔, Office2010的沒測試. 包括.doc,
* .docx, .xls, .xlsx, .ppt, .pptx等. 示例: F:\\office\\source.doc
* @param destFile
* 目標文件. 絕對路徑. 示例: F:\\pdf\\dest.pdf
* @return 操作成功與否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置錯誤; 如果返回 0,
* 則表示操作成功; 返回1, 則表示轉換失敗
*/
public static int office2PDF(String sourceFile, String destFile) {
try {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
return -1;// 找不到源文件, 則返回-1
}
// 如果目標路徑不存在, 則新建該路徑
File outputFile = new File(destFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
// 啓動OpenOffice的服務
String command = "C:/OpenOffice 4/program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
Process pro = Runtime.getRuntime().exec(command);
// connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
connection.connect();
// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(
connection);
converter.convert(inputFile, outputFile);
// close the connection
connection.disconnect();
// 關閉OpenOffice服務的進程
pro.destroy();
return 0;
} catch (FileNotFoundException e) {
e.printStackTrace();
return -1;
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
注意:command字符串中的oppenoffice程序文件找不到:java.io.IOException: Cannot run program "E:\OpenOffice\openoffice4\program\s(解決辦法:把路徑中的空格去掉,從新安裝一遍)
網絡連接問題:java.net.ConnectException: connection failed: socket,host=127.0.0.1,port=8100,tcpNoDelay=1: java.net.ConnectException: Connection refused: connect
未完待續......