Java中使用Runtime和Process类运行外部程序

http://blog.csdn.net/tang08/article/details/1780427

java调用外部进程的blog和一个例子, 找到的写得比较详细的博客
http://jiangshuiy.iteye.com/blog/1674235

可以采用select for update nowait,实现对同一个任务打包的并发控制
http://tech.ccidnet.com/art/1105/20080130/1358017_1.html

文件下载
wget -O photo.jpg http://uuoffsxxxxf


package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaExecCmd {

	public static void main(String args[]) throws Exception{
		execp("rm -rf /opt/cafe/python",null);
		execp("mkdir -p /opt/cafe/python",null);
		writeContent("print('helloworld')","/opt/cafe/python/hello.py");
		writeContent("print(''')","/opt/cafe/python/hello_err.py");
		execp("ls",new File("/opt/cafe/python"));
		//调用返回了正确的结果
		execp("python hello.py",new File("/opt/cafe/python"));
		//调用出现了异常
		execp("python hello_err.py",new File("/opt/cafe/python"));
	}
	static void writeContent(String content,String fpath) throws IOException{
		FileOutputStream fout=new FileOutputStream(fpath);
		fout.write(content.getBytes());
		fout.close();
	}
	public static void execp(String cmd, File dir) throws IOException{
		ExecResult er=exec(cmd,dir);
		System.out.println("exec command:" +cmd);
		System.out.println(er);
		System.out.println();
		System.out.println();
	}
	public static ExecResult exec(String command, File dir) throws IOException {
		ExecResult ret=new ExecResult();
        Runtime rt = Runtime.getRuntime();      
        Process pr = rt.exec(command, null, dir);
        
        BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line=null;
        while((line=input.readLine()) != null) {
        	ret.output+=line+"\n";
        }
        input =  new BufferedReader(new InputStreamReader(pr.getErrorStream()));
        while((line=input.readLine()) != null) {
        	ret.errout+=line+"\n";
        }
        try{
        	ret.code = pr.waitFor();
    	 }
        catch(InterruptedException e){
        	ret.code=-1;
        }
		return ret;
	}
	/**
	 * 执行返回的数据结构
	 */
	static class ExecResult{
		//外部程序返回的错误码,0表示执行成功
		int code;
		//外部程序的标准输出stdout
		String output="";
		//外部程序的标准错误输出stderr
		String errout="";
		public String toString(){
			return "code:"+code+",output:"+output+",errout:"+errout;
		}
	}
}


猜你喜欢

转载自wangqiaowqo.iteye.com/blog/2252671