Other applications [Java] calls this machine

We just want to learn programming can compile a program can perform a series of operations to third-party process. For example: Open QQ a text message to a friend to the bombing. Well, today we take a first step toward calling a third-party process:

package com.mfs.io;

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

/*
 * 调用本机的其他应用
 */
public class OSExcute {
	
	public static void command (String c) throws IOException { //参数c是cmd命令
		ProcessBuilder builder = new ProcessBuilder(c.split(" "));  //创建一个进程
		Process process = builder.start();  //开始此进程
		/*
		 * getInputStream()方法获取该进程的在控制台的输出信息
		 */
		BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
		String s;
		while ((s = br.readLine()) != null) {
			System.out.println(s);
		}
		/*
		 * getErrorStream()方法获取该进程的错误流
		 */
		BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
		while ((s = err.readLine()) != null) {
			System.out.println(s);
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			command("cmd /c D:/helloworld.py"); //调用helloworld.py;命令的写法与平常在cmd写一样
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

Published 57 original articles · won praise 55 · views 1930

Guess you like

Origin blog.csdn.net/qq_40561126/article/details/104953088