码迷,mamicode.com
首页 > 编程语言 > 详细

Java调用Linux命令(cd的处理)

时间:2017-05-30 23:18:45      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:time()   input   dwr   close   独立   连接   tput   linux系统   style   

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

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

 1     public String executeLinuxCmd(String cmd) {
 2         System.out.println("got cmd job : " + cmd);
 3         Runtime run = Runtime.getRuntime();
 4         try {
 5             Process process = run.exec(cmd);
 6             InputStream in = process.getInputStream();
 7             BufferedReader bs = new BufferedReader(new InputStreamReader(in));
 8             // System.out.println("[check] now size \n"+bs.readLine());
 9             String result = null;
10             while (in.read() != -1) {
11                 result = bs.readLine();
12                 System.out.println("job result [" + result + "]");
13             }
14             in.close();
15             // process.waitFor();
16             process.destroy();
17             return result;
18         } catch (IOException e) {
19             e.printStackTrace();
20         }
21         return null;
22     }

二、含有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长连接,保持连接,发送多条命令,最后释放连接。

示例逻辑代码:

 1 public void executeNewFlow() {
 2         Runtime run = Runtime.getRuntime();
 3         File wd = new File("/bin");
 4         System.out.println(wd);
 5         Process proc = null;
 6         try {
 7             proc = run.exec("/bin/bash", null, wd);
 8         } catch (IOException e) {
 9             e.printStackTrace();
10         }
11         if (proc != null) {
12             BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
13             PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
14             out.println("cd /home/test");
15             out.println("pwd");
16             out.println("rm -fr /home/proxy.log");
17             out.println("exit");
18             try {
19                 String line;
20                 while ((line = in.readLine()) != null) {
21                     System.out.println(line);
22                 }
23                 proc.waitFor();
24                 in.close();
25                 out.close();
26                 proc.destroy();
27             } catch (Exception e) {
28                 e.printStackTrace();
29             }
30         }
31     }

 

Java调用Linux命令(cd的处理)

标签:time()   input   dwr   close   独立   连接   tput   linux系统   style   

原文地址:http://www.cnblogs.com/yoyotl/p/6914096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!