一、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. 【ES】elasticsearch学习笔记

    ES学习 1 优势 1.1 简单 1.1.1 相比Solor配置部署等非常简单 1.2 高效 1.2.1 ES使用Netty作为内部RPC框架,Solor使用Jetty 1.3 插件化 1.3.1 E ...

  2. 给 TextBlock 加 ToolTip

    <TextBlock ToolTip="{Binding RelativeSource={RelativeSource Self},Path=Text}" Text=&quo ...

  3. [转]DOM 中 Property 和 Attribute 的区别

    angular的文档: https://angular.io/guide/template-syntax#property-binding https://blog.csdn.net/sunq1982 ...

  4. python 初步学习

    疑惑1:windows下的python  如何设置显示汉字 推荐几个学习网址,也方便自己以后查看: http://pmghong.blog.51cto.com/3221425/d-10 www.w3c ...

  5. C# GDI+技术

    C# GDI+技术 GDI+概述         GDI+是GDI(即Windows早期版本号中附带的Graphics Device Interface)的后继者.它是一种构成Windows XP操作 ...

  6. Swift学习笔记-1

    Apple官方开发手冊地址: https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/La ...

  7. google/protobuf/releases/tag/v3.4.0 下载

    Protocol Buffers v3.4.0 Downloads 4.07 MB protobuf-cpp-3.4.0.tar.gz 5.02 MB protobuf-cpp-3.4.0.zip 4 ...

  8. [Functional Programming 101] runWIth, evalWith, execWith

    Recentlly, I am learning crocks.js ADT libaray. In the beginning, it is hard to understand when to u ...

  9. C++:fread、fwrite函数用法

    主要内容: fread.fwrite函数的用法 1.函数功能 用来读写一个数据块. 2.一般调用形式 fread(buffer,size,count,fp); fwrite(buffer,size,c ...

  10. U盘去保护方法

    一.基本信息 U盘大小是16G的,估计用了2G的空间存储,没有任何开关设置,格式化或写入时提示被写保护: U盘放到任何一台电脑上都是只能读不能写,说明与电脑无关,用了各种U盘修复程序都无效: 二.一般 ...