使用Runtime.exec()运行windwos dos或linux shell命令,按实际情况具体测试
 
 
实例代码:
package com.bookoo.test.command;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
 
/**
 *
 * @author nathan
 */
public class TestLinuxCommand {
      public static void main(String[] args) {
      String logDir = System.getProperty("log.dir");
      
      
      // windows "/c"参数一定要加上 打开窗口立即关闭,获取读写流不会报异常
      String commands = "cmd.exe /c c: && dir";
      
      // linux
//          String commands = "ls -l";
//          String commands = "sh -c cd /data/log/daemon/bprocess && ls -lt";
//          String[] commands = new String[] {"/bin/sh", "-c", "/bin/ls -lt /data/log/daemon/bprocess"};
 
      
      /**
       *  测试1:用命令字符串数组运行函数执行多个命令<br>
       *  运行流程:打开sh窗口-->执行pwd命令-->over<br>
       *  结果运行只运行了第一个命令<br>
       *  为什么了,经过测试发现,这个函数他根本就不用管有几个命令,只需要将这个数组组成一个字符串去运行,你数组的内容组成一条字符串是什么样,那运行结果就是什么样了(运行不了就报错误呗)<br>
       *  疑问:那这样的话,我如何运行多个命令了,查语法发现多个一起运行可以用"&&"符号,如:"dir &&dir d:&& e:"(空格是没有关系的)<br>
       *  好,上面是dos运行的情况,现在再看linux<br>
       *  shell只是数组中的第一条字符串pwd运行了,后面一个命令没有运行,原理跟dos是一样的,组成一个字符串运行有问题,加"&&"符号隔开两个命令就ok了<br>
       *  猜想:那好,如果只能运行一条字符串,那我不用数组了,看测试2
       */
      // windows dos
      // String[] commands = new String[] {"cmd.exe", "/c", "dir" ,"d:", "dir"};
      // String[] commands = new String[] {"cmd.exe", "/c", "dir" ,"&&d:&&", "dir"};
      // linux shell
      // 错误,还是只执行一个pwd命令,ls命令不执行,正确用法看测试2
      // String[] commands = new String[] {"/bin/sh", "-c", "pwd" , "/bin/ls"};
      // String[] commands = new String[] {"/bin/sh", "-c", "ls" , "&& pwd"};
      
      
      /**
       * 测试2:用命令字符串运行函数执行多个命令<br>
       * 运行流程:打开sh窗口-->执行pwd命令-->执行ls命令-->over<br>
       * 结果证明测试1结果猜想是正确的<br>
       */
      // windwos dows
      // String commands = "cmd.exe /c dir && c: && dir";
      // linux shell
      // ls命令不执行,参数没效果
      // String commands = "sh -c pwd&&ls -lt";
      // 正确,ls参数没效果
      // String commands = "sh -c ls -lt&&pwd";
      
      /**
       * 测试3:不同环境下切换目录命令<br>
       * windows可行,linux不可行<br>
       * 疑问:只要能够dos或者shell中测试的一整条命令,exec就能运行,但linux切换目录命令一加就不行<br>
       */
      // windows
      // String commands = "cmd.exe /c dir && c: && dir";
      // linux
      // 错误
      // String commands = "sh -c pwd && cd /data/log/daemon/bprocess && ls -lt";
      // 正确,ls参数没生效
      // String commands = "sh -c ls -lt /data/log/daemon/bprocess && pwd";
      // 正确,ls参数生效,神奇吧,前面不用加sh一样能运行且这样运行ls参数生效,但是pwd命令用不了,原因没在schell环境中,单独运行加sh -c 就行了
      // String commands = "/bin/ls -lt /data/log/daemon/bprocess && pwd";
      // 错误
      // String[] commands = new String[] {"/bin/sh", "-c", "pwd" ,"cd /data/log/daemon/bprocess", "/bin/ls"};
      
      // 这样的话,schell环境下执行,我要想看哪个目录文件,就不能先切换过去在看了,命令写成这样:/bin/ls -lt /data/log/daemon/bprocess
      // dos也是一样的 dir c:
      
      /**
       * 最后<br>
       * cmd.exe=cmd(大写也行),sh=/bin/sh(schell命令都是在/bin目录下),操作结果都是一样的,不会报错<br>
       * /bin/sh这种写法执行为了调用更安全(直接告诉命令在哪,不要linux自己再去识别一下了,我是这样猜想的)<br>
       */
      java.lang.Process process = null;
      try
            {
            System.out.println("exec commands success");
            process = Runtime.getRuntime().exec(commands);
            InputStreamReader inputStream = new InputStreamReader(process.getInputStream());
            BufferedReader input = new BufferedReader(inputStream);
            String line;
            System.out.println("print inputStream start");
            while ((line = input.readLine()) != null){
                  System.out.println(line);
            }
            System.out.println("print inputStream over");
            
//                InputStreamReader errorStream = new InputStreamReader(process.getErrorStream());
//                input = new BufferedReader(errorStream);
//                System.out.println("print errorStream start");
//                while ((line = input.readLine()) != null){
//                      System.out.println(line);
//                      input.close();
//                }
//                System.out.println("print errorStream over");
            
//                OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream());
//                BufferedWriter writer = new BufferedWriter(outputStream);
//                System.out.println("print outputStream start");
//                writer.write("outputStream writer success");
//                writer.flush();
//                writer.close();
//                System.out.println("print outputStream over");
            } catch (IOException e)
            {
                  System.out.println("have ioexception");
                  e.printStackTrace();
            } finally{
                  try
                  {
                        System.out.println(process.waitFor());
                  } catch (InterruptedException e)
                  {
                        e.printStackTrace();
                  }
            }
      }
}
 
 
 
 
搜索关键词:java 运行linux命令

java使用Runtime.exec()运行windwos dos或linux shell命令的更多相关文章

  1. Java运行系统命令并获取值(Process java.lang.Runtime.exec(String[] cmdarray, String[] envp, File dir)

    package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; ...

  2. [转]Java中Runtime.exec的一些事

    0 预备知识 1 不正确的调用exitValue 2不正确的调用waitFor 3 一种可接受的调用方式 4 调用认为是可执行程序的时候容易发生的错误 5 window执行的良好示例 6 不良好的重定 ...

  3. Java文件操作API功能与Windows DOS命令和Linux Shell 命令类比

    Java文件操作API功能与Windows DOS命令和Linux Shell 命令类比: Unix/Linux (Bash) Windows(MS-DOS) Java 进入目录 cd cd - 创建 ...

  4. DOS 和 Linux 常用命令的对比

    DOS 和 Linux 常用命令的对比 许多在 shell 提示下键入的 Linux命令都与你在 DOS 下键入的命令相似.事实上,某些命令完全相同. 本附录提供了 Windows的 DOS 提示下的 ...

  5. 解决java使用Runtime.exec执行linux复杂命令不成功问题

    最近要实现一个Java调用一个复杂shell命令实现数据同步,该命令有管道重定向的语句,结果硬是执行不成功,而且也没异常报出.经过一段时间的折腾终于解决了此问题,权当做备忘记录下来(重点在红色框中的“ ...

  6. java.lang.Runtime.exec() Payload Workarounds

    由于Runtime.getRuntime().exec()中不能使用管道符等bash需要的方法,我们需要用进行一次编码 编码工具: 地址: http://jackson.thuraisamy.me/r ...

  7. java执行linux shell命令,并拿到返回值

    package com.pasier.xxx.util; import java.io.IOException; import java.io.InputStream; import java.nio ...

  8. 为什么windows dos和Linux shell有这样的差别??

    Windows dos随着impdp导入数据库: impdp "sys/password@ip:1521/sidname as sysdba" directory=dbdir du ...

  9. Java利用 ganymed-ssh2-build.jar来上传文件到linux以及下载linux文件以及执行linux shell命令

    package api; import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.IOExcepti ...

随机推荐

  1. 【BZOJ1717】[Usaco2006 Dec]Milk Patterns 产奶的模式 (二分+SA)

    求重复k次的最长重复子串,解法见罗穗骞大神的后缀数组论文 ; var x,y,rank,sa,h,s,num,c:..maxn] of longint; n,time:longint; functio ...

  2. python百度贴吧爬虫

    # -*- coding: utf-8 -*- #coding=utf-8 import urllib import urllib2 import re import thread import ti ...

  3. id_rsa id_rsa.pub

    id_rsa  私钥 id_rsa.pub  公钥 https://blog.csdn.net/qq_36663951/article/details/78749217 https://blog.cs ...

  4. :nth-child :nth-type-of用法详解

     ele:nth-of-type(n) 是指父元素下ele元素里的第n个ele:nth-child(n) 是指父元素下第n个元素且这个元素为ele 

  5. HTML 对空行和空格进行控制

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  6. 问题:viewController不会调用dealloc()不会销毁

    问题 在调试程序时,我从ViewController A push进 ViewController B,在从B back时发现程序不会执行B里面的dealloc(),很诡异的问题,因为按理说此时点击b ...

  7. HDU 4779:Tower Defense

    Tower Defense Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 132768/132768 K (Java/Others)T ...

  8. linux解决无法打开资源管理器

    前两天升级系统,使用命令pacman -Syyu,大概是使用的是testing缘故,今天发现dolphin无法打开了,使用命令行打开,提示ldmp.so有问题. 解决方法如下: 一,使用命令:pacm ...

  9. 九、 Java程序初始化的顺序(二)

    之前的一篇博客里我写了关于在一个类中的程序初始化顺序,但是在Java的面向对象里,类之间还存在着继承的关系.所以关于程序的初始化顺序,我们可以再细划分为:父类静态变量,父类的静态代码块,父类构造器,父 ...

  10. Scrapy学习-25-Scrapyd部署spider

    Scrapyd部署爬虫项目 github项目  https://github.com/scrapy/scrapyd    官方文档  http://scrapyd.readthedocs.org/  ...