一、首先是OpenOffice的进程关闭的问题,原因比较多,大多数是文件转换失败,导致服务崩溃。
如文件过大,字符集不识别等。 通过两个批处理文件,监控soffice.exe进程,如果没有,则重新启动,
openOffice.bat 始终启动,监控进程,如果没有则执行run.bat
@echo off
:loop
tasklist|find /i "soffice.exe"
if %errorlevel%==1 (
call "run.bat"
)
ping -n 6 127.0.0.1>nul
goto loop
run.bat 启动OpenOffice服务
@echo off
c:
cd C:\Program Files (x86)\OpenOffice 4\program\
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
P:
DocumentConverter converter = new OpenOfficeDocumentConverter( connection);
converter.convert(inputFile, outputFile);
//这个方法没有返回值,在转换失败的情况下,出现卡死的现象,如OpenOffice服务失效或者关闭的情况,其他原因不明。
在出现上面的情况下,就需要规定转换时间,在规定时间内必须返回,如无返回,则认为转换失败。
//按规定时间执行需要用到 FutrueTask
ExecutorService executor = Executors.newSingleThreadExecutor();
FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
//使用Callable接口作为构造参数
public String call() {
boolean c = coverToPdf(DocCover.tFileName );
// 封装好的转换方法,你可以认为是converter.convert(inputFile, outputFile);
if(c == true){
return "1";
}else{
return "0";
}
//call方法要求返回字符串
}});
executor.execute(future);
try {
String result = future.get(15000, TimeUnit.MILLISECONDS);
//设置超时执行时间为15秒,超过时间限制抛出超时异常
if(result.equals("1")){
//说明执行成功,继续代码即可
}
} catch (InterruptedException e) {
break;
} catch (ExecutionException e) {
break;
} catch (TimeoutException e) {
System.out.println("超时");
//因为不知道什么原因,杀掉进程,跳出,因为有一、中的进程监控,
//所以进程会自动重启,不会影响下一个转换
Runtime.getRuntime().exec("taskkill /F /im soffice.exe*");
break;
} finally {
executor.shutdown(); }