有时候我们想用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();
- }
- }
- }
- }
执行结果: