java实现liunx,windows命令的调用 需要2个类:Process,Runtime
其中我们要了解:
Process exec(String command) 在单独的进程中执行指定的字符串命令。
Process exec(String command, String[] envp) 在指定环境的单独进程中执行指定的字符串命令。
Process exec(String command, String[] envp, File dir) 在有指定环境和工作目录的独立进程中执行指定的字符串命令。
Process exec(String[] cmdarray) 在单独的进程中执行指定命令和变量。
Process exec(String[] cmdarray, String[] envp) 在指定环境的独立进程中执行指定命令和量。
Process exec(String[] cmdarray, String[] envp, File dir) 在指定环境和工作目录的独立进程中执行指定的命令和变量。
其中
使用Runtime来执行command,生成Process对象 连接到cmd,其中cmd里liunx和windows有一定的区别
代码如下:
package yr;
import java.io.PrintWriter;
public class cmdTe {
//windows下
public static void windowsCmd() throws Exception {
Process p=Runtime.getRuntime().exec("cmd");//连接windows的cmd
PrintWriter ps=new PrintWriter(p.getOutputStream());//输入命令
ps.println("e:");
ps.println("cd /");
ps.println("mkdir azj");
ps.println("cd azj");
ps.println("echo success > azj.txt");
ps.close();//关闭流
new Thread(new SyncPipe(p.getInputStream(), System.out,null)).start();
}
//liunx下
public static void liunxCmd() throws Exception {
String [] as={"/bin/sh","-c","ls -l; exit"};//java调用liunx命令是通过shell进行调用的 ,想要输入多个命令如:String [] as={"/bin/sh","-c","ls -l; touch /home/a.txt;exit"}红色调用sh命令(必须的),绿色调用的指令
Process p=Runtime.getRuntime().exec(as);
new Thread(new SyncPipe(p.getInputStream(),null,new StringBuffer())).start();
}
public static void main(String[] args) throws Exception {
liunxCmd();
}
}
package com.azj.cmd;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm,StringBuffer s) {
istrm_ = istrm;
ostrm_ = ostrm;
StringBuffer = s;
}
public void run() {
try{
if(null !=ostrm_){
System.out.println("com windows");//windows cmd
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1;){
ostrm_.write(buffer, 0, length);//输出命令及显示的结果
}
istrm_.close();
ostrm_.close();
}else{
System.out.println("com liunx"); //liunx cmd
BufferedReader br=new BufferedReader(new InputStreamReader(istrm_));
String line;
if((line=br.readLine())!=null){
StringBuffer.append(line).append("\n");//输出命令及显示的结果
}
System.out.println(StringBuffer.toString());
istrm_.close();
}
}
catch (Exception e) {
throw new RuntimeException("处理命令出现错误:"+e.getMessage());
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
private final StringBuffer StringBuffer;
}