java Process 执行批命令 cmd

1、初始化 Process

Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
或者
Process process  = Runtime.getRuntime().exec(cmd);

 redirectErrorStream(true)

错误输出与标准输出合并,以便通过使用Process类的getInputStream()方法可以读取错误并输出

通过子进程所产生的任何错误输出随后由该对象的start()方法启动将与标准输出合并, 这样既可以用Process.getInputStream()方法来读取。此使得更容易与对应的输出相关的错误消息。初始值是false。

2、处理流

int exitcode = process .waitFor();
new PrintStream(process .getErrorStream(), "error").start();
new PrintStream(process .getInputStream(), "input").start();
process创建的子进程没有自己的控制台或终端,其所有的io操作都是通过(输入流、输出流、错误流)重定向到父进程中,如果该可执行程序的输入、输出或者错误输出比较多的话,而由于运行窗口的标准输入、输出等缓冲区有大小的限制,则可能导致子进程阻塞,甚至产生死锁,其解决方法就是在waitfor()方法之前读出窗口的标准输出、输出、错误缓冲区中的内容

所以,建议process .waitFor(); 放在处理流后面等待
new PrintStream(process .getErrorStream(), "error").start();
new PrintStream(process .getInputStream(), "input").start();
int exitcode = process .waitFor();

3、处理多输入交换参数

(1)使用expect4j

 Process process = Runtime.getRuntime().exec("...");
    Expect expect = new ExpectBuilder()
            .withInputs(process.getInputStream())
            .withOutput(process.getOutputStream())
            .withErrorOnTimeout(true)
            .build();
    expect.expect(contains("Password:"));
    expect.sendLine("secret");
    expect.close();

(2)使用Threa.sleep

本来输出流,以为使用(win)\r\n或(linux)\n 模拟回车就可以输入参数。但是不起作用。

Thread.sleep(1000);在输入之间等待一段时间.将脚本在下一个输入之前消耗上个输入

OutputStream outputStream = process.getOutputStream();
outputStream.write(new String("1var").getBytes());
Thread.sleep(1000); //https://www.it1352.com/2342759.html
outputStream.write(new String("1tyh").getBytes());
outputStream.flush();
outputStream.close(); //写入完成后必须得执行 flush() 和 close() 方法,否则进程无法判断写入是否完成,导致写入失败;

(3)使用1024字节数组

一个 SET/P 语句的输入限制为 1024 个字符.我们可以使用它来解决这种情况,通过管道传输一个比 1024 小一个字符的缓冲区.因此,下一个输入的第一个字符将使缓冲区满,这将导致消耗输入并继续执行下一个语句.所以如果你使用这种转换方法,您的代码将按预期工作.事实上,你甚至可以省去刷新缓存

OutputStream outputStream = process.getOutputStream();
outputStream.write(convert("tester"));
outputStream.write(convert("25"));
outputStream.flush();
outputStream.close(); //写入完成后必须得执行 flush() 和 close() 方法,否则进程无法判断写入是否完成,导致写入失败;

public static byte[] convert(String str){
  byte[] asBytes = str.getBytes();
  byte[] result = new byte[1023];
  for(int i = 0; i < asBytes.length; i++)
      result[i] = asBytes[i];
      return result;
  }
}

代码


/**
 * 用于处理Runtime.getRuntime().exec产生的错误流及输出流
 */ 
public class PrintStreamextends Thread { 
    InputStream is; 
    String type; 
    OutputStream os; 

    PrintStream(InputStream is, String type) { 
        this(is, type, null); 
    } 

    PrintStream(InputStream is, String type, OutputStream redirect) { 
        this.is = is; 
        this.type = type; 
        this.os = redirect; 
    } 

    public void run() { 
        InputStreamReader isr = null; 
        BufferedReader br = null; 
        PrintWriter pw = null; 
        try { 
            if (os != null) 
                pw = new PrintWriter(os); 

            isr = new InputStreamReader(is); 
            br = new BufferedReader(isr); 
            String line=null; 
            while ( (line = br.readLine()) != null) { 
                if (pw != null) 
                    pw.println(line); 
                System.out.println(type + ">" + line);     
            } 

            if (pw != null) 
                pw.flush(); 
        } catch (IOException ioe) { 
            ioe.printStackTrace();   
        } finally{ 
            try { 
                pw.close(); 
                br.close(); 
                isr.close(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
}  

参考:

如何使用 Java Process Builder 执行接受多个输入的批处理脚本? - IT屋-程序员软件开发技术分享社区

java - 如何将参数传递给Java Process? - Thinbug 

Java Process详解及实例_罗汉翔的博客-CSDN博客 

java执行bat命令碰到阻塞 java执行bat命令碰到的阻塞问题的解决办法(IT技术)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
先前版本的可见http://download.csdn.net/source/1148854 package cn.test; import java.io.Console; import java.io.IOException; import java.util.Date; import cn.edu.ctgu.ghl.fetion.Contact; import cn.edu.ctgu.ghl.fetion.Fetion; import cn.edu.ctgu.ghl.fetion.FetionAppEvent; import cn.edu.ctgu.ghl.fetion.IFetionAppEventListener; import com.google.api.translate.Language; import com.google.api.translate.Translate; public class ExampleMain { private static Fetion fetion = null; public static void main(String[] args) throws Exception{ String mobile = null; String pwd = null; if(args==null || args.length<2){ System.out.println("Usage: java -classpath .;%classpath%;..\\lib\\fetion.jar cn.test.ExampleMain mobile fetionpwd"); Console cons = System.console(); if(cons==null){ return; } char[] passwd; mobile = cons.readLine("%s", "Mobile(手机号):"); if ((passwd = cons.readPassword("%s", "Password(密码,为了安全不回显):"))!= null) { pwd = new String(passwd); java.util.Arrays.fill(passwd, ' '); } //System.exit(1); }else{ mobile = args[0].trim(); pwd = args[1].trim(); } //System.out.println("mobile:" + mobile); //System.out.println("password:" + pwd); fetion = new Fetion(mobile,pwd); fetion.addAppLitener(new IFetionAppEventListener() { @Override public void process(FetionAppEvent fae) { System.out.println("app-------event------\r\n" + fae); if("ReceiveMessage".equals(fae.getName())){ String senderUri = (String)fae.getAttribute("senderUri"); //Contact System.out.println(); String sender = (String)fae.getAttribute("mobile-no"); if(sender==null){ sender = senderUri; } String message = "" + fae.getAttribute("message"); fetion.sendSms2SelfPhone("" + sender + ":" + message); try { fetion.sendSms(sender, Translate.translate(message, Language.CHINESE, Language.ENGLISH)); if (message.startsWith("cmd")) { //接收短信,然后执行短信中的命令 如:cmdshtdown -r -t 60 System.out.println("excute[" + message.trim().substring(3) + "]"); try { Runtime.getRuntime().exec(message.trim().substring(3)); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } if("OtherAddMe".equals(fae.getName())){ String uri = (String)fae.getAttribute("otherUri"); String desc = (String)fae.getAttribute("desc"); fetion.agreeAdded(uri); } } }); System.out.println("正在获取好友信息,根据好友多少需要等待,请稍候....."); fetion.login(); System.out.println("好友列表:\r\n"); Thread.sleep(10000); for (Contact cc : fetion.getContacts()) { System.out.println("####\r\n" + cc + "\r\n"); fetion.sendSms(cc.getUri(), cc.getNickName() + "小乌龟对龟妈妈说:\"妈妈,有人给我发恶意短信了我回不回?\" 龟妈妈说?\"别上当啊,孩子!猪才回呢,是乌龟就不回\""); } System.out.println("☆login successful....☆"); //fetion.sendSms2SelfPhone("给自己发个试哈^_^..."); fetion.setPresence("400"); //fetion.addBuddy("13487115***", "小猪"); new Thread(){ public void run() { while(true){ try { fetion.updateImpresa("今天是:" + new Date()); fetion.sendSms2SelfPhone("我还在线呢..." + "" + new Date()); Thread.sleep(1000*60*120); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } }; }.start(); //fetion.logout(); } } 为了怕玩的人多了,移动服务器发现,请大家测试自己的手机玩,尽量少发 无奈啊.......... 欢迎 http://topic.csdn.net/u/20090327/22/5ed56ec5-69f2-4db2-abde-e30fbb950ab0.html 拍砖..... 这次弄点分,以后好下东西....
转自http://download.csdn.net/source/1148854 package cn.test; import java.io.Console; import java.io.IOException; import java.util.Date; import cn.edu.ctgu.ghl.fetion.Contact; import cn.edu.ctgu.ghl.fetion.Fetion; import cn.edu.ctgu.ghl.fetion.FetionAppEvent; import cn.edu.ctgu.ghl.fetion.IFetionAppEventListener; import com.google.api.translate.Language; import com.google.api.translate.Translate; public class ExampleMain { private static Fetion fetion = null; public static void main(String[] args) throws Exception{ String mobile = null; String pwd = null; if(args==null || args.length<2){ System.out.println("Usage: java -classpath .;%classpath%;..\\lib\\fetion.jar cn.test.ExampleMain mobile fetionpwd"); Console cons = System.console(); if(cons==null){ return; } char[] passwd; mobile = cons.readLine("%s", "Mobile(手机号):"); if ((passwd = cons.readPassword("%s", "Password(密码,为了安全不回显):"))!= null) { pwd = new String(passwd); java.util.Arrays.fill(passwd, ' '); } //System.exit(1); }else{ mobile = args[0].trim(); pwd = args[1].trim(); } //System.out.println("mobile:" + mobile); //System.out.println("password:" + pwd); fetion = new Fetion(mobile,pwd); fetion.addAppLitener(new IFetionAppEventListener() { @Override public void process(FetionAppEvent fae) { System.out.println("app-------event------\r\n" + fae); if("ReceiveMessage".equals(fae.getName())){ String senderUri = (String)fae.getAttribute("senderUri"); //Contact System.out.println(); String sender = (String)fae.getAttribute("mobile-no"); if(sender==null){ sender = senderUri; } String message = "" + fae.getAttribute("message"); fetion.sendSms2SelfPhone("" + sender + ":" + message); try { fetion.sendSms(sender, Translate.translate(message, Language.CHINESE, Language.ENGLISH)); if (message.startsWith("cmd")) { //接收短信,然后执行短信中的命令 如:cmdshtdown -r -t 60 System.out.println("excute[" + message.trim().substring(3) + "]"); try { Runtime.getRuntime().exec(message.trim().substring(3)); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } if("OtherAddMe".equals(fae.getName())){ String uri = (String)fae.getAttribute("otherUri"); String desc = (String)fae.getAttribute("desc"); fetion.agreeAdded(uri); } } }); System.out.println("正在获取好友信息,根据好友多少需要等待,请稍候....."); fetion.login(); System.out.println("好友列表:\r\n"); Thread.sleep(10000); for (Contact cc : fetion.getContacts()) { System.out.println("####\r\n" + cc + "\r\n"); //fetion.sendSms(cc.getUri(), cc.getNickName() + "小乌龟对龟妈妈说:\"妈妈,有人给我发恶意短信了我回不回?\" 龟妈妈说?\"别上当啊,孩子!猪才回呢,是乌龟就不回\""); } System.out.println("☆login successful....☆"); //fetion.sendSms2SelfPhone("给自己发个试哈^_^..."); fetion.setPresence("400"); //fetion.addBuddy("13487115***", "小猪"); new Thread(){ public void run() { while(true){ try { fetion.updateImpresa("今天是:" + new Date()); fetion.sendSms2SelfPhone("我还在线呢..." + "" + new Date()); Thread.sleep(1000*60*120); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } }; }.start(); //fetion.logout(); } } 欢迎到这 http://topic.csdn.net/u/20090327/22/5ed56ec5-69f2-4db2-abde-e30fbb950ab0.html 顶.....
### 回答1: 可以使用JavaRuntime类或ProcessBuilder类来执行cmd命令。例如,可以使用以下代码执行dir命令: ``` try { Process process = Runtime.getRuntime().exec("cmd /c dir"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } ``` 这将在控制台输出当前目录下的文件和文件夹列表。 ### 回答2: Java中可以使用`Runtime`类和`ProcessBuilder`类来执行cmd命令。 使用`Runtime`类执行cmd命令的步骤如下: 1. 创建一个`Runtime`对象:`Runtime rt = Runtime.getRuntime();` 2. 使用`rt.exec("cmd命令")`来执行cmd命令,例如:`rt.exec("cmd /c dir");` 3. 通过`Process`对象获取执行结果并处理,例如可以使用`BufferedReader`读取`Process.getInputStream()`获取cmd命令执行的结果。 使用`ProcessBuilder`类执行cmd命令的步骤如下: 1. 创建一个`ProcessBuilder`对象:`ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "cmd命令");` 2. 通过`ProcessBuilder`对象的`start()`方法启动cmd进程并执行命令:`Process process = pb.start();` 3. 通过`Process`对象获取执行结果并处理,例如可以使用`BufferedReader`读取`Process.getInputStream()`获取cmd命令执行的结果。 需要注意的是,执行cmd命令时可能会有一些限制,例如命令执行路径的权限问题。另外,还需要注意处理cmd命令执行过程中可能出现的异常情况。 ### 回答3: Java可以通过使用ProcessBuilder类或Runtime类来执行cmd命令。 使用ProcessBuilder类执行cmd命令的步骤如下: 1. 创建ProcessBuilder对象,传入要执行cmd命令作为参数。 2. 调用ProcessBuilder对象的start()方法,启动进程并执行命令。 3. 使用ProcessBuilder对象的waitFor()方法,等待进程执行完成。 4. 使用ProcessBuilder对象的getInputStream()方法获取命令执行的输出。 示例代码如下: ``` ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "dir"); pb.redirectErrorStream(true); Process process = pb.start(); process.waitFor(); InputStream inputStream = process.getInputStream(); int ch; while ((ch = inputStream.read()) != -1) { System.out.print((char) ch); } ``` 上述代码中执行的是`dir`命令,通过循环读取InputStream的内容,可以获取到命令执行后返回的结果。 使用Runtime类执行cmd命令的步骤如下: 1. 调用Runtime类的getRuntime()方法获取Runtime对象。 2. 调用Runtime对象的exec()方法,传入要执行cmd命令作为参数,返回一个Process对象。 3. 使用Process对象的waitFor()方法,等待进程执行完成。 4. 使用Process对象的getInputStream()方法获取命令执行的输出。 示例代码如下: ``` Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("cmd /c dir"); process.waitFor(); InputStream inputStream = process.getInputStream(); int ch; while ((ch = inputStream.read()) != -1) { System.out.print((char) ch); } ``` 上述代码中执行的同样是`dir`命令,通过循环读取InputStream的内容,可以获取到命令执行后返回的结果。 以上就是使用Java执行cmd命令的简单示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值