0 0

如何编写一个command line程序?0

如何编写一个command line程序?
用java可以做出command line程序吗?
2014年5月14日 15:38

5个答案 按时间排序 按投票排序

1 0

我之前正好做了一个java 调用shell 脚本或者bat脚本的工具类,供楼主参考
为了防止命令进程阻塞,添加两线程处理输出信息

package utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

import vo.ResponseData;

public class CallCmdUtils {
	
	private static Logger logger = Logger.getLogger(CallCmdUtils.class);
	
	public static void executeCmd(String cmd){
		if(cmd == null || cmd.equals("")){
			return;
		}
		logger.info("执行命令:"+cmd);

		String[] cmds = new String[]{"/bin/sh","-c",cmd};
		try {
			Runtime.getRuntime().exec(cmds);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 执行本地命令 cmd格式 windows 环境下查询360运行exe程序: cmd /c tasklist | findstr
	 * "360.*[.exe]"
	 * 
	 * @param cmd
	 * @return
	 */
	public static ResponseData executeLocalCmd(String cmd) {
		if(cmd == null || cmd.equals("")){
			return ResponseData.FAIL_NO_DADA;
		}
		logger.info("执行命令:"+cmd);

		String[] cmds = new String[]{"/bin/sh","-c",cmd};
		StringBuffer sb = new StringBuffer(255);
		ResponseData data = ResponseData.FAIL_NO_DADA;
		try {
			Process process = Runtime.getRuntime().exec(cmds);
			process.waitFor();
			int  result = process.exitValue();
			if(result == 0){
				data.setSuccess(true);
				InputStream in = process.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String dataline = null;
				while ((dataline = br.readLine()) != null) {
					sb.append(dataline).append("\n");
				}
				br.close();
				in.close();
				data.setResult(sb.toString().trim());
			}else{
				InputStream in = process.getErrorStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String dataline = null;
				while ((dataline = br.readLine()) != null) {
					sb.append(dataline).append("\n");
				}
				br.close();
				in.close();
				data.setErrorMsg(sb.toString().trim());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	
	
	public boolean execCommand(String command){
		boolean execFlag = true;
		try {
			Process proc = Runtime.getRuntime().exec(command);
			//为了防止命令进程阻塞,添加两线程处理输出信息
			new StreamGobbler(proc.getErrorStream(),"["+command+"]ERROR").start();
			new StreamGobbler(proc.getInputStream(),"["+command+"]STDOUT").start();
			
        	if(proc.waitFor()==0){
        		logger.error("执行["+command+"]命令成功");
        	}else{
            	logger.error("执行["+command+"]命令出错");
            	execFlag = false;
        	}
        } catch (IOException ex) {
        	logger.error("执行["+command+"]命令IO异常",ex);
        	execFlag = false;
        } catch (InterruptedException ex) {
        	logger.error("执行["+command+"]命令被中断",ex);
        	execFlag = false;
        }
        return execFlag;
	}
}






package utils;

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;  
import java.io.PrintWriter;  

import org.apache.log4j.Logger;
  
/** 
 * 用于处理Runtime.getRuntime().exec产生的错误流及输出流 
 * @author shaojing 
 * 
 */  
public class StreamGobbler extends Thread {
	static Logger logger = Logger.getLogger(StreamGobbler.class);
	
    InputStream is;  
    String type;  
    OutputStream os;  
          
    public StreamGobbler(InputStream is, String type) {  
        this(is, type, null);  
    }  
  
    public StreamGobbler(InputStream is, String type, OutputStream redirect) {  
        this.is = is;  
        this.type = type;  
        this.os = redirect;  
    }  
      
    public void run() {  
        InputStreamReader isr = null;  
        BufferedReader br = null;  
        PrintWriter pw = null;  
        try {  
            if (os != null)  
                pw = new PrintWriter(os);  
                  
            isr = new InputStreamReader(is);  
            br = new BufferedReader(isr);  
            String line=null;  
            while ( (line = br.readLine()) != null) {  
                if (pw != null)  
                    pw.println(line);  
                logger.info(type + ">" + line);      
            }  
              
            if (pw != null)  
                pw.flush();
        } catch (IOException ioe) {  
            ioe.printStackTrace();    
        } finally{  
            if(pw != null){
            	pw.close();
            	pw = null;
            }
            if(isr != null){
            	try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            	isr = null;
            }
            if(br != null){
        	    try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	    br = null;
            }
        }  
    }  
}






2014年5月15日 00:16
0 0

貌似有个开源的框架可以实现类似的功能,名字我不记得了,你可以查一下

2014年5月23日 22:20
0 0

可以啊,java se 在你不使用 swing 时就是命令行程序啊

2014年5月15日 16:18
0 0

 

2014年5月14日 16:13
0 0

可以的, 给你一个简单的ping google的吧

import java.io.BufferedReader;
import java.io.InputStreamReader;
 
public class ExecuteShellComand {
 
	public static void main(String[] args) {
 
		ExecuteShellComand obj = new ExecuteShellComand();
 
		String domainName = "google.com";
 
		String command = "ping -c 3 " + domainName;
 
 
		String output = obj.executeCommand(command);
 
		System.out.println(output);
 
	}
 
	private String executeCommand(String command) {
 
		StringBuffer output = new StringBuffer();
 
		Process p;
		try {
			p = Runtime.getRuntime().exec(command);
			p.waitFor();
			BufferedReader reader = 
                            new BufferedReader(new InputStreamReader(p.getInputStream()));
 
                        String line = "";			
			while ((line = reader.readLine())!= null) {
				output.append(line + "\n");
			}
 
		} catch (Exception e) {
			e.printStackTrace();
		}
 
		return output.toString();
 
	}
 
}

2014年5月14日 15:44

相关推荐

Global site tag (gtag.js) - Google Analytics