Java調用Linux命令(cd的處理)


一、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());
         
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() + "]");
14             in.close();
15             // process.waitFor();
16             process.destroy();
17             return result;
18         } catch (IOException e) {
19             e.printStackTrace();
20         }
21         return null;
22     }

 

二、含有管道符(|)多級命令串聯查詢

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長連接,保持連接,發送多條命令,最后釋放連接。

示例邏輯代碼:

 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");//這個命令必須執行,否則in流不結束。 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     }

 三的優化和演進(返回值)

    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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM