天天看点

java调用Windows命令行

java来调用windows的命令,一般情况下下面两行代码即可实现:

以下为完整的例子:

public class OSExecute {

	/**
	 *
	 * */
	public static void command(String command){
		boolean err=false;
		try {
			Process process=new ProcessBuilder(command.split(" ")).start();
			BufferedReader results=new BufferedReader(new InputStreamReader(process.getInputStream()));
			String s;
			while((s=results.readLine())!=null)
				System.out.println(s);
			BufferedReader errors=new BufferedReader(new InputStreamReader(process.getErrorStream()));
			while((s=errors.readLine())!=null){
				System.err.println(s);
				err=true;
			}



		} catch (Exception e) {
			// TODO Auto-generated catch block
		   if(!command.startsWith("CMD /C"))
			   command("CMD /C"+command);
		   else
			   throw new RuntimeException(e);
		}

		if(err)
			throw new OSExecuteException("Error executing:"+command);

	}
}


public class OSExecuteException extends RuntimeException{

	public OSExecuteException(String why) {
		super(why);
	}
}


public class OSExecuteDemo {

	public static void main(String[] args){
		OSExecute.command("ipconfig/all");
	}
}
           

继续阅读