您的位置:首页 > 编程语言 > Java开发

Java外部执行操作系统命令(Java 创建本地系统进程)

2010-04-14 10:59 656 查看

Java外部执行操作系统命令 Java 创建本地系统进程

Java线程机制、Process、ProcessBuilder,对启用的进程in/out/error信息进行记录
级别: 初级

王延成 (ybygjy@gmail.com)

2010 年 4 月 13 日(整理)

此文章内容主要描述了Java Process、ProcessBuilder类的使用,在使用中遇到的问题处理。

在我们web应用中,有几个地方需要用到本地系统进程来处理,如:

使用Process启用系统的某个服务

定时执行文件格式转换

应用程序自动重启

执行系统定时备份,数据库备份

当然,使用java执行本地系统应用程序也只是我们解决问题的一种办法,我们也可以使用别的手段来解决。

要注意的小细节 ·本地系统环境变量
配置本地系统环境变量的目的就是能让Java VM 找的到外部应用程序,我们一定都还记得java环境变量怎么配置吧?。在配置完环境变量后,我们就可以在创建系统进程时指定java vm 去哪里找操作系统命令(具体见代码)。

·监听进程执行过程中的标准/异常输出





回页首
代码示例

这段代码包含在基于FlashPaper的文档只读文档所和代码中.

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hd.sy.util.doc.FileConvert;
import com.hd.util.HDException;
/**
 * 文件转换swf格式支持
 * @author WangYanCheng
 * @version 2009-12-3
 */
public class FileConvert4SwfImpl implements FileConvert {
    /**转换完成后的文件名称*/
    private File fileInst = null;
    /**输出目录*/
    private File outFolder = null;
    /**
     * {@inheritDoc}
     * 需要验证fileInst是否为空
     */
    public File doConvertFile(File inputFileInst, File outFilePath) throws HDException {
        new InnerConvertThread(inputFileInst, outFilePath);
        return fileInst;
    }
    /**
     * {@inheritDoc}
     * 需要验证fileInst是否为空
     */
    public File doConvertFile(File inputFileInst) throws HDException {
        new InnerConvertThread(inputFileInst, null);
        return fileInst;
    }
    /**
     * setOutFolder
     * @param setOutFolder setOutFolder
     */
    public void setOutFolder(File setOutFolder) {
        this.outFolder = setOutFolder;
    }
    /**
     * {@inheritDoc}
     */
    public String getCommand() {
        return defaultCommand;
    }
    /**
     * {@inheritDoc}
     */
    public void setCommand(String tmpCommand) {
        this.defaultCommand = tmpCommand;
    }
    /**default command*/
    private String defaultCommand = "FlashPrinter.exe";
    /**
     * InnerConvert
     * @author WangYanCheng
     * @version 2009-12-4
     */
    class InnerConvertThread implements Runnable {
        /**inputFile*/
        private File inFile = null;
        /**outFilePath*/
        private File outFile = new File(System.getProperty("java.io.tmpdir"));
        /**
         * Constructor
         * @param inFileObj inFileObj
         * @param outFilePath outFilePath
         */
        public InnerConvertThread(File inFileObj, File outFilePath) {
            this.inFile = inFileObj;
            this.outFile = outFilePath == null ? outFolder : outFilePath;
            Thread th = new Thread(this);
            //th.setDaemon(true);
            th.start();
        }
        /**
         * Constructor
         * @param setInFile input file to set
         * @param setOutFolder output Folder to set
         */
        public InnerConvertThread(String setInFile, String setOutFolder) {
            this.inFile = new File(setInFile);
            this.outFile = null == setOutFolder ? outFile : new File(setOutFolder);
            new InnerConvertThread(inFile, outFile);
        }
        /**
         * {@inheritDoc}
         */
        public void run() {
            String tmpOutFile = outFile.getPath()
                .concat(File.separator).concat(inFile.getName().replaceAll("[.]{1}.*$", ".swf"));
            fileInst = new File(tmpOutFile);
            List commandArray = new ArrayList();
            commandArray.add(defaultCommand);
            commandArray.add(inFile.getPath());
            commandArray.add("-o");
            commandArray.add(tmpOutFile);
            ProcessBuilder pbObj = new ProcessBuilder();
            pbObj.command(commandArray);
            Map envMap = pbObj.environment();
            envMap.clear();
            envMap.putAll(System.getenv());
            pbObj.directory(outFile);
            pbObj.redirectErrorStream(true);
            try {
                Process proObj = pbObj.start();
                final InputStream ins = proObj.getInputStream();
                final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                Thread th = new Thread() {
                    public void run() {
                        ReadableByteChannel rbcObj = Channels.newChannel(ins);
                        while(true){
                        try {
                            while (rbcObj.read(byteBuffer) != -1) {
                                byteBuffer.flip();
                                logger.info(java.nio.charset.Charset.defaultCharset().decode(byteBuffer));
                                byteBuffer.clear();
                            }
                        } catch (IOException e) {
                            logger.error(e);
                        }
                        }
                    }
                };
                th.setDaemon(true);
                th.start();
                try {
                    proObj.waitFor();
                    logger.error("转换完成." + tmpOutFile);
                } catch (InterruptedException e) {
                    logger.error(e);
                }
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }
    /**
     * 测试入口
     * @param args 参数列表
     */
    public static void main(String[] args) {
        File inputFileInst = new File("D://work//workspace//mywork//src//org//ybygjy//file//cv2Swf//file//servlet-2_3-fcs-spec.pdf"),
        outputFileInst = new File("D://work//workspace//mywork//src//org//ybygjy//file//cv2Swf//file//");
        FileConvert fc = new FileConvert4SwfImpl();
        try {
            fc.doConvertFile(inputFileInst, outputFileInst);
        } catch (HDException e) {
            e.printStackTrace();
        }
    }
    /**logger*/
    private Log logger = LogFactory.getLog(FileConvert4SwfImpl.class);
}







回首页
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: