一、Java调用Linux系统的命令非常简单

这是一个非常常用的调用方法示例:

     public String executeLinuxCmd(String cmd) {
System.out.println("got cmd job : " + cmd);
Runtime run = Runtime.getRuntime();
try {
Process process = run.exec(cmd);
InputStream in = process.getInputStream();
BufferedReader bs = new BufferedReader(new InputStreamReader(in));
// System.out.println("[check] now size \n"+bs.readLine());
         StringBuffer out = new StringBuffer();
         byte[] b = new byte[8192];
         for (int n; (n = in.read(b)) != -1;) {
           out.append(new String(b, 0, n));
        }
         System.out.println("job result [" + out.toString() + "]");
             in.close();
// process.waitFor();
process.destroy();
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

二、含有管道符(|)多级命令串联查询

public List<String> executeLinuxCmd(String cmd) {
System.out.println("got cmd job : " + cmd);
Runtime run = Runtime.getRuntime();
try {
// Process process = run.exec(cmd);
Process process = run.exec(new String[] {"/bin/sh", "-c", cmd});
InputStream in = process.getInputStream();
BufferedReader bs = new BufferedReader(new InputStreamReader(in));
List<String> list = new ArrayList<String>();
String result = null;
while ((result = bs.readLine()) != null) {
System.out.println("job result [" + result + "]");
list.add(result);
}
in.close();
// process.waitFor();
process.destroy();
return list;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

三、含有cd操作的方法示例

1. 问题背景

1.1 java程序运行在/home/lings目录下;

1.2 希望删除/home/test目录下的文件proxy.log;

1.3 调用上面的接口两次?

executeLinuxCmd("cd /home/test");
executeLinuxCmd("rm -fr /home/proxy.log");

是不行的!

1.4 这个接口的调用是单次事务型的,就是每次调用都是独立的事务或者说操作,没有关联的。

那这种“复杂”一点的操作流程怎么办呢?

1.5 方法a: 可以写一个独立的脚本,然后一次运行脚本,这样多复杂的逻辑都没问题。

1.6 方法b: 可以启动一个shell长连接,保持连接,发送多条命令,最后释放连接。

示例逻辑代码:

 public void executeNewFlow() {
Runtime run = Runtime.getRuntime();
File wd = new File("/bin");
System.out.println(wd);
Process proc = null;
try {
proc = run.exec("/bin/bash", null, wd);
} catch (IOException e) {
e.printStackTrace();
}
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
out.println("cd /home/test");
out.println("pwd");
out.println("rm -fr /home/proxy.log");
out.println("exit");//这个命令必须执行,否则in流不结束。
try {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}

三的优化和演进(返回值)

    public List<String> executeNewFlow(List<String> commands) {
List<String> rspList = new ArrayList<String>();
Runtime run = Runtime.getRuntime();
try {
Process proc = run.exec("/bin/bash", null, null);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
for (String line : commands) {
out.println(line);
}
// out.println("cd /home/test");
// out.println("pwd");
// out.println("rm -fr /home/proxy.log");
out.println("exit");// 这个命令必须执行,否则in流不结束。
String rspLine = "";
while ((rspLine = in.readLine()) != null) {
System.out.println(rspLine);
rspList.add(rspLine);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return rspList;
}

Java调用Linux命令(cd的处理)的更多相关文章

  1. Java调用Linux命令执行

    调用方式 Java调用linux命令执行的方式有两种,一种是直接调用linux命令,一种是将linux命令写到.sh脚本中,然后调用脚本执行. 详细说明 直接调用:使用java中lang包下面的Run ...

  2. java调用Linux命令报错:java.io.IOException: Cannot run program "ps": CreateProcess error=2, ?????????

    在idea里面,java代码:Runtime.getRuntime().exec("ps -aux") 是因为默认是用windows平台运行了,所以报错,得改成调用Linux平台运 ...

  3. java 调用 linux 命令行 +使用管道、awk等命令进行数据处理的方法

    这里用 sh -c "命令" 的方式是因为java里只能这么用,管道这边java处理不了,所以只能一次执行一条命令,但是在linux里用 sh -c 的方式返回的awk处理过的结果 ...

  4. Java调用Linux命令

    // int tp = 1 返回执行结果  非1 返回命令执行后的输出 public static String runCommand(String cmd, int tp) { StringBuff ...

  5. java调用Linux执行Python爬虫,并将数据存储到elasticsearch--(环境脚本搭建)

    java调用Linux执行Python爬虫,并将数据存储到elasticsearch中 一.以下博客代码使用的开发工具及环境如下: 1.idea: 2.jdk:1.8 3.elasticsearch: ...

  6. java基础/java调用shell命令和脚本

    一.项目需求: 从某一机构获取证书,证书机构提供小工具,执行.sh脚本即可启动服务,本地调用该服务即可获取证书. 问题:linux服务器启动该服务,不能关闭.一旦关闭,服务即停止. 解决方案:java ...

  7. php通过system()调用Linux命令问题

    最近在做php和linux crontab的联调,发现php在linux下的权限问题需要引起注意,调试问题的过程中发现有许多问题前人说的比较零散,我在这里汇总,顺带抛砖引玉一下. 1.$result= ...

  8. scala调用Linux命令行

    在 scala 里面存在 调用 Linux 命令行的函数: import scala.sys.process._ 执行的方法也不难: import scala.sys.process._ /** * ...

  9. Java调用windows命令

    JAVA调用windows的cmd命令 用起来会让程序变得更加简洁明了,非常实用. 核心就是使用 Runtime类. cmd的xcopy就有很强大的文件夹,文件处理功能. 下面就以xcopy来说明,如 ...

随机推荐

  1. jquery选择器用法笔记(第二部分)

    今天继续讲讲jquery选择器的更多用法,希望能给大家带来帮助. 9.$("ul li:eq(3)")  --  列表中的第四个元素(index 从 0 开始) :eq() 选择器 ...

  2. 利用CSS、JavaScript及Ajax实现图片预加载的三大方法及优缺点分析

    预加载图片是提高用户体验的一个很好方法.图片预先加载到浏览器中,访问者便可顺利地在你的网站上冲浪,并享受到极快的加载速度.这对图片画廊及图片占据很大比例的网站来说十分有利,它保证了图片快速.无缝地发布 ...

  3. PHP 使用mysql 与 mysqli 连接Mysql数据库

    代码很简单直接上了 <?php /** * @Author: HTL * @Email: Huangyuan413026@163.com * @DateTime: 2015-05-14 16:0 ...

  4. [Node.js]30. Level 6: Listen 'Question' from client, and then Answer the Question

    Clients can also answer each other questions, so let's build that feature by first listening for the ...

  5. 用10046 跟踪exp

    之前写过一个blog,Oracle expdp为什么比exp快,原理是什么,是从官方文档中获知的,如今通过10046来分析exp的过程. C:\Users\Administrator>exp L ...

  6. Setsockopt选项

    讨论 Setsockopt选项 http://c.chinaitlab.com/cc/ccjq/200806/752042_3.html 总而言之,如果你肯定能一起发送多个数据集合(例如HTTP响应的 ...

  7. js生成pdf报表

    由于前台html已经动态生成报表,而且,前台有一个功能,一个date range组件,当你拖动的时候,报表会在不提交到后台的情况下动态变化.因此需要用到js生成生报表: 用到的组件: jquery.j ...

  8. Android Developers:日历提供者

    <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="ht ...

  9. linux 目录结构(转)

    原文:http://www.centoscn.com/CentOS/2014/1222/4347.html linux 目录结构 /: 根目录,一般根目录下只存放目录,不要存放文件,/etc./bin ...

  10. GIS+=地理信息+容器技术(4)——Docker执行

    -------------------------------------------------------------------------------------- Blog:    http ...