有时候我们想用java去调用系统的命令实现一些功能,这个功能一般比较实用,例如调用word,记事本之类的东西来,用命令就可以了,主要用到了Process process = new ProcessBuilder(command.split(" ")).start();,然后把process里面的信息拿出来,记录一下。

OSException异常:

public class OSException extends RuntimeException {
	public OSException() {
	}
	public OSException(String str) {
		super(str) ;
	}
}

 OSExcute类:

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

public class OSExcute {
	public static void main(String[] args) {
		OSExcute.command("javap -c OSException") ;
	}
	public static void command(String command) {
		boolean err = false;
		try {
			Process process = new ProcessBuilder(command.split(" ")).start();
			BufferedReader result = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String s ;
			while((s = result.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 (IOException e) {
			System.out.println("Exception") ;
			if(!command.startsWith("CMD /C"))
				command("CMD /C"+command) ;
			else 
				throw new RuntimeException(e) ;
		}
		if(err){
			try {
				throw new OSException("Error executing") ;
			} catch (OSException e) {
				e.printStackTrace();
			}
			
		}
	}
}

 执行结果:
运行控制台命令(java)
 

 

相关文章:

  • 2022-12-23
  • 2019-02-09
  • 2022-03-03
  • 2022-03-04
  • 2022-01-07
  • 2021-12-14
  • 2021-07-07
猜你喜欢
  • 2021-10-31
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
  • 2021-09-29
相关资源
相似解决方案